Hamming Distance LeetCode

 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



Approach 1: -

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

        // Convert integer x to a 32-bit binary string with leading zeros
        String a = String.format("%32s", Integer.toBinaryString(x)).replace(' ', '0');

        // Convert integer y to a 32-bit binary string with leading zeros
        String b = String.format("%32s", Integer.toBinaryString(y)).replace(' ', '0');

        // Compare each bit of the two binary strings
        for (int i = 0; i < 32; i++) {
            // If bits are different at the same position, increase the count
            if (a.charAt(i) != b.charAt(i)) {
                count++;
            }
        }

        // Return the number of differing bits (Hamming Distance)
        return count;
    }
}


Approach 2:


class Solution {
    public int hammingDistance(int x, int y) {
       
        int count = 0;        // To store the number of differing bits
        int mask = 1;         // Bitmask used to check each bit one by one

        // XOR gives a number where bits are 1 if they are different in x and y
        int xor = x ^ y;      // Example: x = 1 (0001), y = 4 (0100) → xor = 0101

        // Check all 32 bits (since integers are 32-bit)
        for (int i = 0; i < 32; i++) {
            // Use bitwise AND to check if the current bit is set (1)
            if ((xor & mask) != 0) {
                count++;      // If bit is 1, it means x and y differ at this bit
            }

            // Move the mask to the left by 1 bit for the next iteration
            mask <<= 1;
        }

        // Return the total number of differing bits (Hamming Distance)
        return count;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence