public class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int c=0;

        while(n>0)

        {

            c=c+n%2;

            n=n/2;

        }

        if(n==1)

            return c+1;

        else

            return c;

    }

}



Input:2147483648 (10000000000000000000000000000000)
Output:0
Expected:1

原因,题目要求int是无符号int型,而java中int是由符号的,因此当输入2147483648时为0而其表示是10000。。。000所以采用二进制的&运算,如下


public class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int s=0;

        while(n!=0)

        {

            s++;

            n=n&(n-1);

        }

        return s;

    }

}