Posts Number of 1 Bits
Post
Cancel

Number of 1 Bits

This question is part of NeetCode150 series.

Problem Description

Write a function that takes 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.

leetcode

Solution

Read about the difference between Logical Right Shift (>>>) and Arithemetic Right Shift (>>):
Right Shifts

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {

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

}
This post is licensed under CC BY 4.0 by the author.