统计二进制中1的个数

本文介绍了一种计算整数二进制表示中1的个数的方法。通过两个函数实现,一种适用于正数,另一种能正确处理负数。通过对输入整数进行位操作,高效地计算出二进制中1的数量。

二进制中1的个数

 

请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。

示例 1:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:

输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution:
    def NumberOf1(self, n):
        count = 0
        while n & 0xffffffff != 0:
            count += 1
            n = n & (n - 1)
        return count

    def NumberOf2(self, n):
        count = 0
        if n<0: # 将负数转为正数
            n = n& 0x7fffffff
            count +=1
        # 每一次都与 1 做 &运算, 判断 N 最右侧是否为 1, 之后不断右移
        # while n!= 0:
        #     if n&1==1:
        #         count += 1
        #     n = n>>1

        while n & 0xffffffff != 0:
            count+=1
            n = n&(n-1)  # 每次使最右侧的 1 变为 0
        return count

if __name__ =="__main__":
    s = Solution()
    num = 102
    r = s.NumberOf2(num)
    print(r)

    r = s.NumberOf1(num)
    print(r)
以下是几种用C++实现统计二进制1个数的函数: ### 方法一 ```cpp #include <iostream> using namespace std; int count_number_of_1(int m) { int c = 0; while (m) { if (m % 2 == 1) { c++; } m /= 2; } return c; } ``` 此方法通过不断对整数进行除以2的操作,判断每一位是否为1统计1个数,原理是利用整数除以2的余数判断当前二进制位是否为1 [^2]。 ### 方法二 ```cpp #include <iostream> #include <math.h> using namespace std; int nums(int n) { int count = 0; while (n != 0) { ++count; n = (n - 1) & n; } return count; } ``` 该方法利用 `(n - 1) & n` 操作,每次操作可以去掉整数二进制表示中最右边的1,通过循环不断去掉1并计数 [^3]。 ### 方法三 ```cpp #include <iostream> using namespace std; int countOnes(unsigned int n) { int a = 0; while (n > 0) { n = n & (n - 1); a++; } return a; } ``` 此方法与方法二类似,同样使用 `n & (n - 1)` 操作去掉最右边的1并计数,不过这里使用 `unsigned int` 类型 [^4]。 ### 方法四 ```cpp class Solution { public: int NumberOf1(int n) { int count = 0; while (n) { ++count; n = (n - 1) & n; } return count; } }; ``` 这是将统计功能封装在类中的实现,同样利用 `(n - 1) & n` 操作统计二进制1个数 [^5]。 ### 方法五 ```cpp class Solution { public: int NumberOf1(int n) { int count = 0; unsigned flag = 1; while (flag) { if (n & flag) { count++; } flag <<= 1; } return count; } }; ``` 该方法通过一个标志位 `flag` 不断左移,与整数 `n` 进行位与操作,判断每一位是否为1统计1个数 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值