LeetCode-191. Number of 1 Bits

来源:互联网 发布:淘宝被骗怎么投诉 编辑:程序博客网 时间:2024/05/21 17:35

问题:https://leetcode.com/problems/number-of-1-bits/?tab=Description
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight). 给定一个无符号数,返回其对应二进制数中1的个数。
For example, the 32-bit integer ’11’ has binary representation
00000000000000000000000000001011, so the function should return 3.
分析:每次左移一位,进行&运算。假设n= 1111000111000 那 n-1 = 1111000110111, (n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说, (n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比下面的快了。有几个1,执行几次。
参考C++代码:

class Solution {public:    int hammingWeight(uint32_t n) {        int count=0;        while(n){            count++;            n=n&(n-1);        }        return count;    }};
0 0
原创粉丝点击