Skip to content

461. Hamming Distance πŸ‘ΒΆ

  • Time: O(32)O(32)
  • Space: O(1)O(1)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def hammingDistance(self, x: int, y: int) -> int:
    ans = 0

    while x > 0 or y > 0:
      ans += (x & 1) ^ (y & 1)
      x >>= 1
      y >>= 1

    return ans
Buy Me A Coffee
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! πŸ˜„