191. Number of 1 Bits

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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的个数-Hamming Weight

2,题目思路
一开始想直接通过逐位&来获得1的个数,但是这样操作的时间代价过于庞大了。
首先,STL中有内置的方法bitset,bitset是用来进行一些状态储存的操作。类似于一个标记数组,又类似于状压里面的二进制。
用法简介:
假设想要将int型数字,创建一个长度为32位的bitset,并统计其中1的个数:

int a = 3;
int counter = bitset<32>(a).count();

bitset基础用法+心得
用这种方法可以很简单的统计1的个数。
去除这种方法,还可以用n & (n-1)的方法,每次都去掉相对最低位的1,然后更新n,直到n为0(去掉所有的1)为止。

3,程序源码

class Solution {
public:
    int hammingWeight(uint32_t n) {
        return bitset<32>(n).count();
};
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res=0;
        while(n)
        {
            n = n & (n-1);
            res++;
        }
        return res;
    }
};

uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名,新瓶装老酒的把戏。不过,不要小看了typedef,它对于你代码的维护会有很好的作用。比如C中没有bool,于是在一个软件中,一些程序员使用int,一些程序员使用short,会比较混乱,最好就是用一个typedef来定义,如:
typedef char bool;

一般来说,一个C的工程中一定要做一些这方面的工作,因为你会涉及到跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以让你最有效的维护你的代码。
按照posix标准,一般整形对应的*_t类型为:
1字节 uint8_t
2字节 uint16_t
4字节 uint32_t
8字节 uint64_t

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值