Python Explanation


  • 8

    We can find the i-th bit (from the right) of a number by dividing by 2 i times, then taking the number mod 2.

    Using this, lets compare each of the i-th bits, adding 1 to our answer when they are different.

    Code:

    ans = 0
    while x or y:
      ans += (x % 2) ^ (y % 2)
      x /= 2
      y /= 2
    return ans
    

  • 0
    C

    @cs307 said in Python Explanation:

    ans = 0
    while x or y:
    ans += (x % 2) ^ (y % 2)
    x //= 2
    y //= 2
    return ans

    x and y should use floor division instead of float division


Log in to reply
 

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