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

来源:互联网 发布:淘宝达人发布完哪里查 编辑:程序博客网 时间:2024/06/16 17:07

一天一道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;    }};
0 0
原创粉丝点击