Number of 1 Bits

原创 2016年08月28日 14:56:33

题目:

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 左一i位与原数相与,为零不是1,非零为1

代码:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int mask=1;
        int res=0;
        for(int i=0; i<32; i++)
        {
            mask=1<<i;
            if(mask&n)
            res++;
        }
        return res;
    }
};


相关文章推荐

【LeetCode】Number of 1 Bits 解题报告

Number of 1 Bits[LeetCode]https://leetcode.com/problems/number-of-1-bits/Total Accepted: 88721 Total...

LeetCode 191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know...

【leetcode】191. Number of 1 Bits

一、题目描述 Write a function that takes an unsigned integer and returns the number of ’1' bits it ha...

Number of 1 Bits

1 Java位运算public class Test { public static void main(String[] args) { // 1、左移( ...

Leetcode 191 Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know...

leetCode 191. Number of 1 Bits

题目链接:https://leetcode.com/problems/number-of-1-bits/     题目内容: Write a function that takes an unsi...

[191] Number of 1 Bits

给定一个整数,统计这个32位整数中1的数量。
  • camlot_
  • camlot_
  • 2016年06月27日 20:23
  • 191

leetcode笔记:Number of 1 Bits

题目的要求很简单,找出一个整数对应的二进制格式中有多少个'1'。

Bit Manipulation - Number of 1 Bits

计算无符号整型中二进制1的数目

LeetCode------Number of 1 Bits

题目简介 Write a function that takes an unsigned integer and returns the number of ’1' bits it has (als...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Number of 1 Bits
举报原因:
原因补充:

(最多只允许输入30个字)