What is the binary representation of -2147483648 in Java int?


  • 0
    S

    One of the general solutions (in Java) for the problem "Number of 1 Bits" is as following by bit manipulation

    public int hammingWeight(int n) {
        int counter = 0;
        while(n != 0){
            counter += n & 1;
            n = n >>> 1;
        }     
        return counter;
    }
    

    I wonder how it solves the problem when n=2147483648? It seems that in Java the largest int is 2147483647, and 2147483648 therefore is represented as -2147483648 due to cyclic representation. But I still don't understand how the above code is able to handle this situation.

    Anyone could shed further light on this? Thanks in advance!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.