Menu Close

Leetcode191: Number of 1 Bits solution

Here, we will help to understand about how to find out Number of 1 Bits solution of leet code 191 with code and algorithm.

You have to write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Example:

Input: n = 00000000000000000000000000011011
Output: 4
Explanation: The input binary string 00000000000000000000000000011011 has a total of four '1' bits.

Input: n = 00000000000000000000000010000010
Output: 2
Explanation: The input binary string 00000000000000000000000010000010 has a total of two '1' bit.

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note: The input must be a binary string of length 32.

Explanation:

This problem belongs to bits category where by using bitwise operator, you have to find out number of set bits in a given number.

Algorithm 1:

  • Iterate over bits of number
    • If bit is 1 then increment the count variable.
    • If bit is 0 then skip the increment the count.
  • return count

Number of 1 Bits code in C++

Code 1:

#include <iostream>

using namespace std;

int hammingWeight(uint32_t n) {
        int count = 0;
        
        while(n) {
            if(n & 1) {
                count++;
            }
            n >>= 1;
        }
        return count;
}

int main()
{
    cout<<hammingWeight(10);

    return 0;
}

Code 2:

#include <iostream>
#include <algorithm>

using namespace std;

int hammingWeight(uint32_t n) {
    int count = 0;
    while (n > 0) {
      count += n & 1;
      n = n >> 1;
    }   
    return count;
 }
  
int main()
{
    cout<<hammingWeight(10);

    return 0;
}

Output:

Input: 10 in bit's: 1010
Output: 2

Output:

abc

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, Leetcode

Leave a Reply

Your email address will not be published.

Contact Us