【LeetCode】面试算法总结@位运算

1、LeetCode—191. 位1的个数

https://leetcode-cn.com/problems/number-of-1-bits/submissions/
在这里插入图片描述

基本思路

#首先我们考虑计算位中的1的个数,我们可以每次右移一位,然后判断数的最后一位是否为一
#如果是我们的结果加一,否则继续移位,直到为0结束
#当n等于0时推出循环,此时ans就是n传入参数中1的个数统计数量
class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        ans = 0
        while n:
            if n & 1:
                ans += 1
            n = n >> 1
        return ans

2、LeetCode—231. 2的幂

https://leetcode-cn.com/problems/power-of-two/submissions/
在这里插入图片描述

基本思路

#通过仔细读题之后发现一个很好的规律
#如果一个数是2的幂,那么这个数与上本身减1是等于0的
#所以根据这样的特性可以得到以下的编码
#非常简洁的代码
class Solution1(object):
    def isPowerOfTwo(self, n):
        if not n:
            return False
        return not(n & (n - 1)) 
#其实代码还可以更加简洁,一行搞定
class Solution2(object):
    def isPowerOfTwo(self, n):
        return n and not(n & (n - 1)) 

3、LeetCode----338. 比特位计数

https://leetcode-cn.com/problems/counting-bits/
在这里插入图片描述

Solution1

#本题与之前做的查找数字n中的二进制表示中1的个数有相似之处
#只是本题中应该是先遍历num,然后针对每个1,2,3,4...num求出对应的二进制表示位中的1的个数
#注意num也是需要计算的,所以遍历的时候应该为range(num + 1)
class Solution1(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ans = []
        for i in range(num + 1):
            temp = 0
            while i:
                if i & 1:
                    temp += 1
                i = i >> 1
            ans.append(temp)
        return ans

Solution2

	#使用python我们如果在多想想,会想到count函数
	#每次遍历将对应的值转换成二进制的表示(bin函数),然后使用count(1)来计数1的个数
	#最后ans.append(temp)计数所有的答案
	class Solution2:
	    def countBits(self, num: int) -> List[int]:
	        ans= []
	        for i in range(num+1):
	            temp= bin(i).count('1')
	            target.append(temp)
	            
	        return ans

Solution3

#如果仔细观察使用数学归纳法可以发现是有规律可循的。
#从0开始
二进制	数	1个数
0000	0	0
0001	1	1
0010	2	1
0011	3	2
0100	4	1
0101	5	2
0110	6	2
0111	7	3
1000	8	1
1001	9	2
#我们将数按照两两一组分组2,3的1的个数:是在1的基础上奇数加1偶数不变
#4、5是在2的基础上奇数加1偶数不变
#6、7是在3的基础上奇数加1偶数不变
#8、9是在4的基础上奇数加1偶数不变
#一次知道我们1的个数表达式的基本规律是:ans[i] = ans[i//2] + i %2
class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ans = [0] * (num+1)
        for i in range(1, num + 1):
            ans[i] = ans[i//2] + i %2
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值