[Lintcode]181. Flip Bits

Posted siriusli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

思路

  • 出错 没有考虑负数的情况


以上是关于[Lintcode]181. Flip Bits的主要内容,如果未能解决你的问题,请参考以下文章

[LintCode] Flip Bits

LintCode刷题笔记--Flip Bits

181. Flip BitsLintCode, by java

Flip the Bits(思维)

[LintCode] Rotate Bits - Left

免除网易云版权