栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

位1的个数,2的幂,比特数记位

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

位1的个数,2的幂,比特数记位

Leetcode地址:191. 位1的个数 - 力扣(LeetCode) (leetcode-cn.com) 常用位运算:

判断奇偶:x&1==1(奇数),xOR0==0(偶数),比取模的效率更高。清除最低位的1:x=x&(x-1)

例:11:1011,清除二进制的1需要三次x&(x-1)运算

step 1:1011&1010=1010

step 2:1010&1001=1000

step 3:1000&111=0

得到最低位的1:x&(-x)<<(左移):符号位不变,低位(右边)补零,eg.100<<2为10000>>(右移):低位溢出,符号位不变,eg.100>>2为1

(如果是负数,先求补码,再移动,再求反码,再加1得到原码。

 剑指offer:Python 二进制中1的个数 &0xffffffff是什么意思?_storyfull-CSDN博客_python中0x是几进制​​​​​​

正数:原码=补码=反码负数:补码=反码+1

题解如下:

时间复杂度为O(m),m为1的个数

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count=0
        while n!=0:
            count+=1
            n=n&(n-1)
        return count

遍历解法:

def hammingWeight(n):
    rst=0
    mask=1
    for i in range(32):#题目要求,输入均为长度32的二进制串
        if n&mask:
        #n有1
            rst+=1
        mask=mask<<1
        #向左移动一位
    return rst
Leetcode:231. 2 的幂 - 力扣(LeetCode) (leetcode-cn.com)

仍然是x&(x-1)的应用

x&(x-1)==0则为2的幂,否则不是

异常处理:0时返回False

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n==0:
            return False
        if n&(n-1)==0:
            return True
        else:
            return False

        #简洁写法
        return n>0 and not n&(n-1)
    

Leetcode:338. 比特位计数 - 力扣(LeetCode) (leetcode-cn.com)
class Solution(object):
    def countBits(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        res=[]
        for i in range(n+1):
            res.append(self.count1(i))
        return res
    
    def count1(self,n):
        count=0
        while n!=0:
            count+=1
            n=n&(n-1)
        return count

其他位运算相关题目:

不用加减乘除做加法_牛客题霸_牛客网 (nowcoder.com)

加法可拆为异或(不进位加法)和与(进位)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号