Number of 1 Bits
Clarify the problem:
- The problem requires counting the number of 1 bits (binary ones) in an unsigned integer.
- We need to implement a function that takes an unsigned integer as input and returns the count of 1 bits.
Analyze the problem:
- Input: An unsigned integer.
- Output: The count of 1 bits.
- Constraints: The input is an unsigned 32-bit integer.
Design an algorithm:
- We can count the number of 1 bits by performing bitwise operations on the input number.
- Initialize a variable
count
as 0 to store the count of 1 bits. - Iterate from 0 to 31 (since the input is a 32-bit integer):
- Check if the current bit is 1 by performing a bitwise AND operation between the input number and a bitmask (1 shifted to the current position).
- If the result is not zero, increment the count by 1.
- Return the final count.
Explain your approach:
- We will implement a function called
hammingWeight
that takes an unsigned integer as input. - Initialize a variable
count
as 0. - Iterate from 0 to 31 and perform bitwise operations to check the bits.
- If a bit is 1, increment the count.
- Return the final count.
- We will implement a function called
Write clean and readable code:
pythondef hammingWeight(n): count = 0 for i in range(32): if n & (1 << i): count += 1 return count
Test your code:
python# Test case 1 # Input: 11 (binary: 1011) # The number of 1 bits is 3. assert hammingWeight(11) == 3 # Test case 2 # Input: 128 (binary: 10000000) # The number of 1 bits is 1. assert hammingWeight(128) == 1 # Test case 3 # Input: 0 # The number of 1 bits is 0. assert hammingWeight(0) == 0
Optimize if necessary:
- The provided solution has a time complexity of O(1) since we iterate through 32 bits, which is a constant number.
- The space complexity is O(1) since we use a constant amount of extra space.
Handle error cases:
- The given code assumes that the input
n
is a valid unsigned 32-bit integer. If the input is not within this range, the behavior is undefined.
- The given code assumes that the input
Discuss complexity analysis:
- The time complexity of the solution is O(1) since we iterate through 32 bits, which is a constant number.
- The space complexity is O(1) since we use a constant amount of extra space to store the count of 1 bits.