位运算
Vaccy Zhu
自律是解决人生问题最主要的工具,也是解决人生痛苦最重要的方法!
展开
-
根据数字二进制下1的数目排序-位运算1356-python
没看答案,位运算。class Solution: def sortByBits(self, arr: List[int]) -> List[int]: # 统计二进制中1的个数 def Hamming(num): count = 0 while num != 0: num = num & (num-1) count += 1原创 2022-05-27 21:07:07 · 94 阅读 · 0 评论 -
只出现一次的数字III-位运算260-python
因为a^a = 0,先遍历数组对所有数异或,得到两个只出现一次的数的异或结果dxor找到dxor最右边的1,令其为tmp。因为两个数对应位不同异或后该位才会为1,所以tmp对应位在两个数中一定是一个为0,一个为1再遍历数组,每个数和tmp与,将所有数分成与运算后为0和为1两组,要找的两个数分别在两组把其中一组的所有数异或,得到其中一个要找的数res,另一个数即为res ^ dxorpythonclass Solution: def singleNumber(self, nums: Li.原创 2021-09-05 16:22:25 · 113 阅读 · 0 评论 -
只出现一次的数字II-位运算137-python
pythonclass Solution: def singleNumber(self, nums: List[int]): res = 0 for i in range(32): count = 0 for num in nums: count += (num >> i) & 1 if count % 3 != 0原创 2021-09-05 15:43:40 · 101 阅读 · 0 评论 -
只出现一次的数字-位运算136-python
pythonclass Solution: def singleNumber(self, nums: List[int]): res = 0 for n in nums: res ^= n return res原创 2021-08-25 17:33:49 · 71 阅读 · 0 评论 -
位1的个数-位运算191-python
pythonclass Solution: def hammingWeight(self, n: int): res = 0 while n != 0: n = n & (n-1) res += 1 return res原创 2021-08-25 16:51:04 · 86 阅读 · 0 评论