HomeLeetcode191. Number of 1 Bits - Leetcode Solutions

191. Number of 1 Bits – Leetcode Solutions

Description

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

Examples:

Example 1:

Input: n = 11

Output: 3

Explanation:

The input binary string 1011 has a total of three set bits.

Example 2:

Input: n = 128

Output: 1

Explanation:

The input binary string 10000000 has a total of one set bit.

Example 3:

Input: n = 2147483645

Output: 30

Explanation:

The input binary string 1111111111111111111111111111101 has a total of thirty set bits.

Solution in Python

Python
class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0  # Initialize the count of set bits to 0
        
        # Loop until all bits in the integer are processed
        while n:
            # Use bitwise AND to check if the least significant bit (LSB) is set (1)
            count += n & 1
            
            # Right shift the integer by 1 bit to process the next bit in the next iteration
            n >>= 1
        
        return count  # Return the total count of set bits

Explanation

  1. Initialization:
    • count is initialized to 0. This variable will keep track of the number of set bits (i.e., bits that are 1).
  2. Loop Through Bits:
    • The while n loop continues as long as n is not 0. This ensures that we process each bit of n.
  3. Check Least Significant Bit:
    • The expression n & 1 checks if the least significant bit (LSB) of n is set (1).
    • If the LSB is 1, we increment count by 1.
  4. Shift Right:
    • We then right shift n by 1 bit using n >>= 1. This effectively discards the LSB we just processed and moves the next bit into the LSB position for the next iteration.
  5. Return the Result:
    • After the loop, count will contain the total number of set bits in the binary representation of n. This is returned as the result.

Example

  • For an input n = 11:
    • Binary representation: 1011
    • The loop processes each bit, finding that there are 3 bits set to 1.
    • The function returns 3.
  • For an input n = 128:
    • Binary representation: 10000000
    • The loop finds 1 bit set to 1.
    • The function returns 1.

This solution efficiently calculates the Hamming weight with a time complexity of O(log n), where n is the number of bits in the integer.

Solution in Javascript

JavaScript
/**
 * @param {number} n
 * @return {number}
 */
var hammingWeight = function(n) {
    let count = 0; // Initialize the count of set bits to 0
    
    // Loop until all bits in the integer are processed
    while (n !== 0) {
        // Use bitwise AND to check if the least significant bit (LSB) is set (1)
        count += n & 1;
        
        // Right shift the integer by 1 bit to process the next bit in the next iteration
        n = n >>> 1; // Use unsigned right shift to ensure correct handling of bits
        
    }
    
    return count; // Return the total count of set bits
};

Solution in Java

Java
class Solution {
    public int hammingWeight(int n) {
        int count = 0; // Initialize the count of set bits to 0
        
        // Loop until all bits in the integer are processed
        while (n != 0) {
            // Use bitwise AND to check if the least significant bit (LSB) is set (1)
            count += n & 1;
            
            // Right shift the integer by 1 bit to process the next bit in the next iteration
            n >>>= 1; // Use unsigned right shift to ensure correct handling of bits
        }
        
        return count; // Return the total count of set bits
    }
}

Solution in C#

C#
public class Solution {
    public int HammingWeight(int n) {
        int count = 0; // Initialize the count of set bits to 0
        
        // Loop until all bits in the integer are processed
        while (n != 0) {
            // Use bitwise AND to check if the least significant bit (LSB) is set (1)
            count += n & 1;
            
            // Right shift the integer by 1 bit to process the next bit in the next iteration
            n = (int)((uint)n >> 1); // Use unsigned right shift to ensure correct handling of bits
        }
        
        return count; // Return the total count of set bits
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular