Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count Number of 1 Bits in java

Tags:

java

bit

I encountered a strange problem while doing an leetcode problem. This is about bits representation in Java.

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

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

My solution is

public class Solution {
// you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; ++i){
            if((n >>> i) % 2 == 1){
                ++count;
            }
        }
        return count;
    }
}

This code is not accepted because of the input case:

4294967295 (11111111111111111111111111111111)

I reviewed the bit representation of integer in java but still do not know the problem of the solution? Could anyone help me?

like image 739
Yun Li Avatar asked Feb 22 '16 06:02

Yun Li


People also ask

How do I count the number of 1 bits in Java?

Java Integer bitCount() method The bitCount() method of Integer class of java. lang package returns the count of the number of one-bits in the two's complement binary representation of an int value. This function is sometimes referred to as the population count.

How do you count 1 binary string?

We can simply count set bits (1's) using __builtin_popcount() .

What is a 1 bit number?

A 1-bit system uses combinations of numbers up to one place value (1). There are just two options: 0 or 1. A 2-bit system uses combinations of numbers up to two place values (11). There are four options: 00, 01, 10 and 11.


3 Answers

public int hammingWeight(int n) {
    return Integer.bitCount(n);
}

Integer.bitCount(int i)

Returns the number of one-bits in the two's complement binary representation of the specified int value.

like image 65
Gayan Weerakutti Avatar answered Oct 21 '22 23:10

Gayan Weerakutti


The issue is performing modulo when you want a bitwise &. Something like,

public static int hammingWeight(int n) {
    int count = 0;
    for (int i = 0; i < 32; ++i) {
        if (((n >>> i) & 1) == 1) {
            ++count;
        }
    }
    return count;
}

public static void main(String[] args) {
    int c = -1;
    System.out.println(hammingWeight(c));
}

Outputs (as expected)

32
like image 20
Elliott Frisch Avatar answered Oct 21 '22 22:10

Elliott Frisch


Java uses twos compliment. So the negative bit is the far left one. That means if you have a number greater than Integer.MAX_VALUE your input will be a negative number. When you do %2the sign remains unchanged. An alternative would be to use &1which will change the sign bit. After the first iteration, and you have done a bit shift, the sign bit will be zero.

like image 39
matt Avatar answered Oct 21 '22 22:10

matt