Leetcode

Hamming Distance

  • Time:O(32)
  • Space:O(1)

C++

class Solution {
 public:
  int hammingDistance(int x, int y) {
    int ans = 0;

    while (x || y) {
      ans += (x & 1) ^ (y & 1);
      x >>= 1;
      y >>= 1;
    }

    return ans;
  }
};

JAVA

class Solution {
  public int hammingDistance(int x, int y) {
    int ans = 0;

    while (x > 0 || y > 0) {
      ans += (x & 1) ^ (y & 1);
      x >>= 1;
      y >>= 1;
    }

    return ans;
  }
}