(LC)191. The number of bits 1

191. Number of Bit 1

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 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.

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: In the input binary string 00000000000000000000000000001011, a total of three bits are '1'.
Example 2:

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

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

prompt:

The input must be a binary string of length 32.

 public int hammingWeight(int n) {
    
    
        int count=0;
        while(n!=0) {
    
    
            n &= n-1;
            count++;
        }
        return count;
    }
```
 

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/115076437