461. Hamming Distance LeetCode Solution

In this guide, you will get 461. Hamming Distance LeetCode Solution with the best time and space complexity. The solution to Hamming Distance problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Hamming Distance solution in C++
  4. Hamming Distance solution in Java
  5. Hamming Distance solution in Python
  6. Additional Resources
461. Hamming Distance LeetCode Solution image

Problem Statement of Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

Constraints:

0 <= x, y <= 231 – 1

Note: This question is the same as 2220: Minimum Bit Flips to Convert Number.

Complexity Analysis

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

461. Hamming Distance LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

461. Hamming Distance LeetCode Solution in 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;
  }
}
// code provided by PROGIEZ

461. Hamming Distance LeetCode Solution in Python

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
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.