LeetCode 191. Number of 1 Bits

Post by ailswan Oct.17, 2023

191. Number of 1 Bits

Problem Statement

link: https://leetcode.com/problems/number-of-1-bits/ https://leetcode.cn/problems/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:

Input: n = 00000000000000000000000010000000 Output: 1

Input: ` n = 11111111111111111111111111111101 **Output:** 31`

Solution Approach

The solution employs bit manipulation to iterate through the binary representation of the integer, counting the number of ‘1’ bits.

Algorithm

  1. Initialization: Start with a counter, res, set to zero which will keep track of the number of ‘1’ bits.
  2. Bitwise Counting: Using a loop, for each bit of the integer n, determine if its least significant bit is ‘1’ by using the bitwise AND operation with 1; increment the res counter if true.
  3. Bitwise Shift: Right-shift the integer n to check the next bit in the subsequent iteration. Continue this process until all bits of n are examined.

Implement

    class Solution:
    def hammingWeight(self, n: int) -> int:
          res = 0
          while n:
              res += n & 1
              n >>= 1
          return res