[leetcode] 191. Number of 1 Bits

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.

Solution

Idea: convert a unsigned integer into binary number

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ret = 0;
        while (n!=0){
            ret += n%2;
            n = n/2;
        }
        return ret;
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51564288
文章标签: leetcode easy
个人分类: leetcode
上一篇[leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
下一篇[leetcode] 326. Power of Three
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭