Accepted Java solution but having a question


  • 1
    Y

    Below is accepted solution.

    public class Solution {
    // accepted solution
    public int hammingWeight(int n) {
        int count=0;
        for(int i=0;i<32;i++){
            count=count+(n&1);
            n=n>>>1;
        }
        return count;
    }
    

    However, when I replaced for loop with while(n>0) loop like below, it gave me an error on testing 2147483648:

    Input: 2147483648 (10000000000000000000000000000000)

    Output: 0

    Expected: 1

    public class Solution {
    // wrong answer after changing for loop into while loop
    public int hammingWeight(int n) {
        int count=0;
        while(n>0){
            count=count+(n&1);
            n=n>>>1;
        }
        return count;
    }
    

    But when I made a little change on while loop condition into while(n!=0), it worked, again.

    public class Solution {
    // accepted again after changing while loop condition
    public int hammingWeight(int n) {
        int count=0;
        while(n!=0){
            count=count+(n&1);
            n=n>>>1;
        }
        return count;
    }
    

    WHY?


  • 3
    M

    Because the unsigned int representation of 2147483648 is -2147483648 which is less than 0. The input of the function is probably Integer.parseUnsignedInt("2147483648") which is a Java 8 function added to deal with unsigned int in Java.


  • 0
    Y

    okay! and one more thing, why isn't 2^32-1 the maximum value of unsigned integer but 2^31?


Log in to reply
 

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