Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011 has a binary representation, so the function should return 3.
The solution to the problem is still very clear.
One, the whole number does not change, the mask shifts right
Use a mast constant with this number to operate and get the corresponding bit whether it is zero
int mask = 1;
int num;
int count = 0;
For shift=0:31
Mask = Mask << shift
int bit = num & mask;
If bit!=0
count++;
End
End
Second, mask unchanged, Integer right Shift method.
This is only suitable for non-negative integers, negative numbers to the right, sign bits will be copied, and eventually become all one.
[Leetcode] Number of 1 bits about bit operation