面试算法总结:位运算
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