首页 > 其他 > 详细

Number of 1 Bits

时间:2015-06-09 23:35:53      阅读:150      评论:0      收藏:0      [点我收藏+]
技术分享
 1 typedef unsigned int uint32_t;
 2 class Solution {
 3 public:
 4     int hammingWeight(uint32_t n) {
 5         int tot=0;
 6         while(n)
 7         {
 8             tot+=n%2;
 9             n>>=1;
10         }
11         return tot;
12     }
13 };
View Code

 这是一道微软的面试题,判断末位是否为1 ,可以用&运算,官方答案是n&(n-1),判断是否为0 ,可以用n&(-n)

Number of 1 Bits

原文:http://www.cnblogs.com/varcom/p/4564789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!