首页 > 代码库 > Number of 1 bits
Number of 1 bits
Brute force solution:
Iterate 32 times, each time determining if the ith bit is a ’1′ or not. This is probably the easiest solution, and the interviewer would probably not be too happy about it. This solution is also machine dependent (You need to be sure that an unsigned integer is 32-bit). In addition, this solution is not very efficient too, as you need to iterate 32 times no matter what.
static int countSetBits(long n) { int count = 0; while(n!=0) { count += n & 1; n >>= 1; } return count; }
Best solution:
Hint: Remember my last post about making use x & (x-1) to determine if an integer is a power of two? Well, there are even better uses for that! Remember every time you perform the operation x & (x-1), a single 1 bit is erased?
The following solution is machine independent, and is quite efficient. It runs in the order of the number of 1s. In the worst case, it needs to iterate 32 times (for a 32-bit integer), but a case such as the number ’8′ would only need to iterate 1 time.
int number_of_ones(unsigned int x) { int total_ones = 0; while (x != 0) { x = x & (x-1); total_ones++; } return total_ones;}
Number of 1 bits