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.public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int i) {
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
}
I do have an easier approach, apparently LeetCode doesn't accept it.
public int hammingWeight(int n) {
int ones = 0;
while(n > 0){
if((n & 1) > 0)
ones++;
n = (n >> 1);
}
return ones;
}
No comments:
Post a Comment