leetcode 191 Hamming Weight

191.

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

 

Java code

int hammingweight(int n)  //因为是32位,所以n要看做无符号整数



{



  int sum =0;  



  while(n!=0){



    if(n&1==1)



    sum++;



    n>>>1;  //n无符号右移一位,即左边补0;注意与>>的区别,>>是有符号右移,例 1001>>1=1000;而1001>>>1=0000



  }



  return sum;
}

你可能感兴趣的:(LeetCode)