algoadvance

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

  1. 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?
  2. Expected Output:
    • Is the expected output an integer indicating the count of ‘1’ bits?

Once clarified, let’s assume:

Strategy

  1. 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.
  2. 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

Explanation

Would you like to proceed with this solution or do you have any additional requirements to consider?

Try our interview co-pilot at AlgoAdvance.com