您的位置:首页 > 其它

【一天一道LeetCode】#191. Number of 1 Bits

2016-07-14 21:10 267 查看

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

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

(二)解题

题目大意:计算一个数的二进制表达式中1的个数

解题思路:剑指offer上的老题了。

把一个整数减去1,然后与原整数做与运算,会把该整数最右边的一个1变成0,要计算1的个数,就循环上述操作,直到这个数为0为止。

class Solution {
public:
int hammingWeight(uint32_t n) {
int num = n;
int count = 0;
while(n)
{
n = n&(n-1);
count++;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: