A little question about overflow


  • 0
    R

    This is my solution of the problem, but it always gives the wrong answer when the input is
    2147483648 (10000000000000000000000000000000)/
    I was wondering if it is about overflow? Why n is not greater than 0 in this case?

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while(n> 0){
                n = n &(n-1);
                count++;
            }
            return count;
        }
    }

  • 1

    @horrible said in A little question about overflow:

    I guess Java treats the integer 10000000000000000000000000000000 as a normal signed integer, which is -2147483648. So.. it's less than 0, and while loop can't get in.

    Simple fix -

    public class Solution {
        public int hammingWeight(int n) {
            int count = 0;
            while(n != 0){
                n = n &(n-1);
                count++;
            }
            return count;
        }
    }

Log in to reply
 

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