Python Explanation

  • 7

    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.


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

Log in to reply

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