Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Example:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string has a total of three '1' bits.
Clarifying Questions
- Input Type and Format:
- What is the type of input? Is it a binary string or an integer?
- Will the input always have exactly 32 bits?
- Expected Output:
- Is the expected output an integer indicating the count of ‘1’ bits?
Once clarified, let’s assume:
- The input is a non-negative integer.
- We need to count the number of ‘1’ bits in its binary representation.
Strategy
- Bit Manipulation Approach - Using Python’s Built-in Functions:
- Convert the integer to its binary representation using the
bin()
function.
- Count the number of ‘1’s in the string representation of the binary number.
- Loop and Bitwise Operation Approach:
- Use a loop to repeatedly check the least significant bit and use a right shift to process the number bit by bit.
- Use the bitwise AND operation to check if the least significant bit is ‘1’.
Code
def hammingWeight(n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return count
Time Complexity
- The time complexity of this approach is (O(1)) because the maximum number of bits to check is constant (32 bits for a standard unsigned integer in most programming environments).
- The space complexity is (O(1)) as well, since we are using a constant amount of space irrespective of the input size.
Explanation
count
is initialized to 0 to keep track of the number of ‘1’ bits.
- In the while loop:
n & 1
checks if the least significant bit of n
is ‘1’ (this is the bitwise AND operation).
- If it is ‘1’, we increment
count
.
n >>= 1
shifts the bits of n
to the right by 1, effectively removing the least significant bit.
- The loop continues until all bits of
n
have been processed (i.e., n
becomes 0).
- Finally, we return the count of ‘1’s.
Would you like to proceed with this solution or do you have any additional requirements to consider?
-
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?