您当前的位置: 首页 >  宝哥大数据

191. 位1的个数(也被称为汉明重量)

宝哥大数据 发布时间:2019-11-10 12:42:33 ,浏览量:2

一、191. 位1的个数

1.1、题目描述

1.2.1、遍历数字的 32 位。如果某一位是 1 ,将计数器加一

class Solution(object):
    def hammingWeight(self, n):
        count = 32
        c = 0
        while count > 0:
            if n&1 == 1:
                c += 1
            n >>= 1
            count -= 1
        return c

1.2.2、位操作

1.3、401. 二进制手表

1.4、693. 交替位二进制数

1.5、762. 二进制表示中质数个计算置位

二、190. 颠倒二进制位

2.1、题目描述

2.2.1、位移

class Solution:
    def reverseBits(self, n):
        res = 0
        count = 32
        while count:
            res = 1     # n右移,为下个循环提供最低位
            count -= 1
        return res

三、231. 2的幂

3.1、题目描述

3.2.1、位运算

class Solution(object):
    def isPowerOfTwo(self, n):
        return n > 0 and (n&(n-1) == 0)

3.3、326. 3的幂

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n  bool:
        # 首先是2的次幂
        if num  int:
        # 异或
        ans = 0
        while x != 0 or y != 0:
            if (x&1) != (y&1):
                ans += 1
            x >>= 1
            y >>= 1
        return ans
关注
打赏
查看更多评论

宝哥大数据

暂无认证

  • 2浏览

    0关注

    985博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录