Number of 1 Bits

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

1,题目要求

Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).

Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three ‘1’ bits.

Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one ‘1’ bit.

Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one ‘1’ bits.

编写一个带无符号整数的函数,并返回它所具有的“1”位数(也称为汉明权重)。

2,题目思路

对于这道题,题目要求求出一个数字中二进制形式所含的1的个数。

在求解这个问题上,最直接和简单的思路,即n和n-1按位&,然后将&的结果再赋值给n,直到n为0。按位&的次数,就是最后的结果。

还有一种讨巧的办法,即STL中有内置的方法bitset,bitset是用来进行一些状态储存的操作。类似于一个标记数组,又类似于状压里面的二进制。
用法简介:
假设想要将int型数字,创建一个长度为32位的bitset,并统计其中1的个数:

参考博客:
bitset基础用法+心得

同时,在这道题中,算法的输入是uint32_t,即:

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

3,代码实现

1,n&(n-1)

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n){
            n = n&(n-1);
            res++;
        }
        return res;
    }
};

2,bitset

class Solution {
public:
    int hammingWeight(uint32_t n) {
        return bitset<32>(n).count();
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值