Table of contents
1. Cyclic checking of binary bits
One, a power of 2
Look at the solution:
Second, the number of bit 1
1. Cyclic checking of binary bits
Ideas and solutions
We can directly loop to check whether each bit of a given integer n is 1.
In the specific code, when checking bit ii, we can make n and 2^i carry out AND operation, if and only when the i bit of n is 1, the operation result is not 0.
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
for (int i = 0; i < 32; i++) {
if (n & (1 << i)) {
ret++;
}
}
return ret;
}
};
Complexity Analysis
Time complexity: O(k), where k is the number of binary digits of type int, k=32. We need to examine each of the binary digits of n, for a total of 32 bits.
Space complexity: O(1), we only need constant space to save several variables.
2. Bit operation optimization
Ideas and solutions
Observe this operation: n & (n−1), the result of the operation is exactly the result of changing the lowest bit of 1 in the binary bits of n to 0.
In this way, we can take advantage of the nature of this bit operation to speed up our checking process. In the actual code, we keep ANDing the current n and n - 1 until nn becomes 0. Because each operation will cause the 1 in the lowest bit of n to be flipped, so the number of operations is equal to the number of 1s in the binary bits of n.
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
while (n) {
n &= n - 1;
ret++;
}
return ret;
}
};
Complexity Analysis
Time complexity: O(logn). The number of cycles is equal to the number of 1's in the binary bits of n, and in the worst case, all the binary bits of n are 1's. We need to loop logn times.
Space complexity: O(1), we only need constant space to save several variables.