[LeetCode] C++: Simple Question-Bit Operation 191. The Number of Bit 1

191. Number of Bit 1

Easy difficulty 251

Write a function, the input is an unsigned integer (in the form of a binary string), and returns the number of digits in the binary expression whose digits are '1' (also known as Hamming weight ).

 

prompt:

  • Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both the input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer is signed or unsigned.
  • In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in  example 3  above, the input represents a signed integer  -3.

 

Advanced :

  • If you call this function multiple times, how would you optimize your algorithm?

 

Example 1:

Input: 00000000000000000000000000001011
 Output: 3
 Explanation: Input binary string00000000000000000000000000001011 中,共有三位为 '1'。

Example 2:

Input: 00000000000000000000000010000000
 Output: 1
 Explanation: In the input binary string 00000000000000000000000010000000  , a total of one bit is '1'.

Example 3:

Input: 11111111111111111111111111111101
 Output: 31
 Explanation: In the input binary string 11111111111111111111111111111111 , a total of 31 bits are '1'.

 

prompt:

  • The input must be 32 a  binary string of length   .

 

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n != 0){
            if((n & 1) != 0){
                res += 1;
            }
            n = n >> 1;
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113754562