LeetCode 461: Hamming Distance Solution

Master LeetCode problem 461 (Hamming Distance), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

461. Hamming Distance

Problem Explanation

Explanation

To calculate the Hamming distance between two integers, we can XOR the two numbers to find the bits that are different. Then, we count the number of set bits in the XOR result to get the Hamming distance. We can do this by repeatedly shifting the XOR result to the right and checking the least significant bit if it is set.

  • Time complexity: O(log n), where n is the maximum number of bits in the input integers x and y.
  • Space complexity: O(1)

Solution Code

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        while (xor > 0) {
            count += xor & 1;
            xor >>= 1;
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 461 (Hamming Distance)?

This page provides optimized solutions for LeetCode problem 461 (Hamming Distance) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 461 (Hamming Distance)?

The time complexity for LeetCode 461 (Hamming Distance) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 461 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 461 in Java, C++, or Python.

Back to LeetCode Solutions