181. Flip Bits

題目

https://www.lintcode.com/problem/flip-bits/description?_from=ladder&&fromId=2

實現

  1. 使用 ^ xor 操作符直接算出 xor 的結果
  2. 然後去數 xor 結果裏 1 出現的次數

代碼

class Solution:
    """
    @param a: An integer
    @param b: An integer
    @return: An integer
    """
    def bitSwapRequired(self, a, b):
        xor = a ^ b
        
        count = 0
        for i in range(32):
            if xor & (1 << i) != 0:
                count += 1
        
        return count
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章