[Lintcode]181. Flip Bits

181. Flip Bits

  • 本题难度: Easy
  • Topic: Math&Bit Manipulation

Description

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.

Notice
Both n and m are 32-bit integers.

我的代码

class Solution:
    """
    @param a: An integer
    @param b: An integer
    @return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        ff=pow(2,32)#注意负数
        a_r = (a + ff)%ff
        b_r = (b + ff)%ff
        count = 0
        while ((a_r or b_r) != 0):
            a_b = a_r % 2
            b_b = b_r % 2
            count += (a_b != b_b)
            a_r = a_r // 2
            b_r = b_r // 2
        return count

思路

  • 出错 没有考虑负数的情况
posted @ 2019-02-10 02:42  siriusli  阅读(113)  评论(0编辑  收藏  举报