Number of 1 Bits LeetCode Solution - The Coding Shala

Home >> LeetCode >> Number of 1 Bits

 In this post, we will learn how to find the Number of 1 Bits in a given integer and will implement its solution in Java.

Number of 1 Bits Problem

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

Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty-one '1' bits.

Practice this problem on LeetCode(Click Here).

Number of 1 Bits Java Solution

Approach 1

We can use Java's bitCount() method to get the number of 1 bits.

Java Program: 

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        return Integer.bitCount(n);
    }
}

Approach 2

By using bit shifting unsigned operation (>>>).

Java Program: 

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int ans = 0;
        while(n !=0) {
            if((n & 1) == 1) ans++;
            n = n >>> 1;
        }
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala