I found out that in python, if you use
bin:>>> bin(4) '0b100' >>> bin(-4) '-0b100'but if you try this:
-4 >> 8 => -1
in fact, when right shift more than 3 bits, the answer is always -1. I know this is implementation stuff, but I came across this problem:
In the following array, find out the number which appears only once, while others appears always three times
[-2,-2,1,1,-3,1,-3,-3,-4,-2]
This is the code
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == None:
return None
ans = 0
for i in range(32):
numOfI = 0
for num in nums:
if (( num >> i) & 1) == 1 :
numOfI += 1
numOfI %=3
print i,numOfI
if numOfI != 0:
ans = ans + (numOfI << i)
return ans
the answer should be -4, but instead I get 11111111111111111111111111111100; how can I convert it into -4?