【LeetCode】191_Number of 1 Bits

来源:互联网 发布:dnf趣味数据网址 编辑:程序博客网 时间:2024/06/06 12:58

题目

Number of 1 Bits

 Total Accepted: 43643 Total Submissions: 115129My Submissions

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即可。很简单

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









0 0