码迷,mamicode.com
首页 > 其他好文 > 详细

leedcode 191 Hamming Weight

时间:2015-03-15 22:52:06      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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;

}

leedcode 191 Hamming Weight

标签:

原文地址:http://www.cnblogs.com/likailiche/p/4340495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!