1. Topic
Please implement a function, an integer input, the output binary number represents the number 1. For example, to 9 is expressed as a binary 1001, there is a 2 1. Thus, if the input 9, the function output 2.
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,
共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,
共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,
共有 31 位为 '1'。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
2. Problem Solving
n&(n-1)
The resulting number than then
binary one less1
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
n = n&(n-1);
count++;
}
return count;
}
};