1.题目描述
在一个数组中除了一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。
2.解题思路
将所有出现三次数字的二进制表示的对应位都加起来,每一位的和都能被3整除。将所有数字的二进制表示的对应位都加起来,如果某一位能被三整除,那么只出现一次的数字在该位为0;反之,为1。
3.代码实现
class Solution(object):
def findNumberAppearingOnce(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in range(32):
count = 0
for num in nums:
# 不要忘记 & 1
if (num >> i) & 1:
count += 1
if count % 3:
res += 1 << i
return res
if __name__ == '__main__':
nums = [1, 0, 0, 0, 2, 1, 1]
solution = Solution()
result = solution.findNumberAppearingOnce(nums)
print(result)