191. Number of 1 Bits

Write a function that takes the binary representation of an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
     
Example 1:
Example 2:
Example 3:
Constraints:
  • The input must be a binary string of length 32.

From: LeetCode
Link: 191. Number of 1 Bits


Solution:

Ideas:
  1. Function Signature:
  • The function hammingWeight takes a single parameter n of type uint32_t. This is a standard unsigned 32-bit integer in C.
  1. Count Variable:
  • A variable count is initialized to 0. This will keep track of the number of ‘1’ bits in the integer.
  1. Looping Through Each Bit:
  • The code uses a for loop to iterate through each of the 32 bits in the integer. The loop variable i goes from 0 to 31, representing each bit position in the integer.
  1. Bitwise AND to Check Bit Value:
  • Inside the loop, a bitwise AND operation is performed between n and (1U << i).
  • 1U is an unsigned integer with a value of 1. The << operator is the left shift operator. 1U << i shifts the number 1 to the left by i places, effectively creating a mask where only the i-th bit is set to ‘1’, and all other bits are 0.
  • The AND operation (n & (1U << i)) checks whether the i-th bit of n is 1 or 0. If this bit in n is 1, the result of the AND operation will be non-zero (true), and if this bit in n is 0, the result will be zero (false).
  1. Counting ‘1’ Bits:
  • If the result of the bitwise AND is non-zero, the count is incremented. This means that the i-th bit in n is 1.
  1. Returning the Count:
  • After the loop completes, the function returns the count of ‘1’ bits.
Code:
int hammingWeight(uint32_t n) {
    int count = 0;
    for (int i = 0; i < 32; i++) {
        if (n & (1U << i)) {
            count++;
        }
    }
    return count;
}
11-13 08:38