Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
,
so the function should return 3.
>>
is
arithmetic shift right, >>>
is
logical shift right.
In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.
For example: -2 represented in 8 bits would be 11111110
(because
the most significant bit has negative weight). Shifting it right one bit using arithmetic shift would give you 11111111
,
or -1. Logical right shift, however, does not care that the value could possibly represent a number; it simply moves everything to the right and fills in from the left with 0s. Shifting our -2 right one bit using logical shift would give 01111111
.
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int result=0;
for(; n!=0; n=n>>>1){
result+=n&1;
}
return result;
}
}