Java Question


  • 0
    V

    Can anyone explains what wrong with this code?

    public int hammingWeight(int n) {
            int count=0;   
            while(n!=0)
            {
                count+=n%2;
                n=n/2;
            }
            return count;
    }
    

    The code wasn't accepted by leetcode until I changed it to

            int count=0;
            while(n!=0)
            {
                if(n%2!=0)count++;
                n=n>>>1;
            }
            return count;
    

    However, both of the codes failed when n=2147483648 in my compiler.
    Error msg: /temp/file.java:58: error: integer number too large: 2147483648.
    Why was the second way accepted but the first one not?


Log in to reply
 

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