Bit manipulation formulas
For nonnegative 32-bit inputs, clear the lowest set bit once per loop iteration.
| Test bit k | (x >> k) & 1 | Use a valid shift count |
| Toggle bit k | x XOR (1 << k) | Each toggle reverses that bit |
| Clear lowest one | x & (x−1) | Works for positive x |
| Power of two | x > 0 and (x & (x−1)) == 0 | Zero is excluded |
Python
def count_ones(x):
count = 0
while x:
x &= x-1
count += 1
return countC++
int countOnes(unsigned x) {
int count = 0;
while (x) { x &= x-1; ++count; }
return count;
}Java
static int countOnes(int x) {
int count = 0;
while (x != 0) { x &= x-1; count++; }
return count;
}