The problem is tagged with Bit Manipulation. So I tried to convert the solution of Java version (count bits) into python one. However, I got unexpected result.
The problem might be about the sign bit. Can anyone share how to solve the sign bit problem in python? That will be much appreciated.
class Solution: def majorityElement(self, num): ones, zeros, result = 0, 0, 0 for digit in range(32): ones = 0; zeros = 0 for element in num: if ((element >> digit) & 1) == 1: ones += 1 else: zeros += 1 if ones > zeros: result |= 1 << digit return result
int has no overflow, it is converted to
long automatically. You should fix it yourself. Py3 has no
long at all. Only
r = 0 for d in range(32): o = 0; z = 0 for e in num: if ((e & (1 << d)) != 0): o += 1 else: z += 1 if o > z: r |= (1 << d) if r & 0x80000000: r = -((r^0xffffffff) + 1) #r = -0x100000000 + r