-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path137_Single_Number_II.py
31 lines (30 loc) · 1.01 KB
/
137_Single_Number_II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution(object):
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# import ctypes
# # note that if res is not c 32
# # there will be errors
# count = [0] * 32
# res = ctypes.c_int32(0)
# for i in range(32):
# for num in nums:
# if (ctypes.c_int32(num).value >> i) & 1:
# count[i] += 1
# res.value |= ((count[i] % 3) << i)
# return res.value
def singleNumber(self, nums):
# bitmask
# ones as a bitmask to represent the ith bit had appeared once.
# twos as a bitmask to represent the ith bit had appeared twice.
# threes as a bitmask to represent the ith bit had appeared three times.
ones, twos, threes = 0, 0, 0
for num in nums:
twos |= ones & num
ones ^= num
threes = ones & twos
ones &= ~threes
twos &= ~threes
return ones