# Any solution using python to count bits?

• 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.

Output:
2147483648

Expected:
-2147483648

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
``````

}

• Py' `int` has no overflow, it is converted to `long` automatically. You should fix it yourself. Py3 has no `long` at all. Only `int`: http://python3porting.com/differences.html

``````        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
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.