Leetcode 191. Number of 1 Bits
Write a function hammingWeight that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
0.We can solve this problem in several ways, but the most straightforward method is to iterate through each bit of the number and count the number of ‘1’ bits.
0.1.1, increment the count.#include <iostream>
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n != 0) {
count += (n & 1); // Increment count if the last bit is 1
n >>= 1; // Right shift n by 1
}
return count;
}
};
int main() {
Solution sol;
uint32_t n = 11; // Example input: binary representation of 11 is 1011
std::cout << "Number of 1 bits: " << sol.hammingWeight(n) << std::endl;
return 0;
}
The time complexity of this solution is O(1) because the number of iterations is fixed (32 times) for a 32-bit integer. Each operation inside the loop is constant time.
The space complexity is O(1) as we are only using a few integer variables for counting and bit manipulation without any additional data structures.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?