卖萌的弱渣

I am stupid, I am hungry.

Flip Bits

Flip Bits

Determine the number of bits required to flip if you want to convert integer n to integer m.

Example

Given n = 31 (11111), m = 14 (01110), return 2.

Note

Both n and m are 32-bit integers.

Solution

if a<0, a’s binary = 232 - abs(a)

(Flip-Bits.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    """
    @param a, b: Two integer
    return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        result = 0
        # if a<0, then a's binary is 2^32 - abs(a)
        if a < 0:
            a = 2**32 + a
        if b < 0:
            b = 2**32 + b
        while a!=0 or b!=0:
            if a%2 != b%2:
                result +=1
            a /= 2
            b /= 2
        return result