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, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

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.

 class Solution {
    public int hammingDistance(int x, int y) {
        String str = Integer.toBinaryString(x^y);
        return str.replaceAll("0","").length();
    }
}


Here, we are going to solve in more easiest way. The hint hidden in this problem is, we need to convert integer to binary and compare both for any differences in 1's position.

1) Do XOR for both numbers.(XOR of same digits (0, 1) will be same). From this, we get difference in 1's position, but it will be in int type.
2) Convert int to binary using toBinaryString().
3) Replace all 0's and length after replacing will be the output.

Related Post:

Click here for April month challenges with solution and explanation

Click Follow button to receive latest updates from us instantly.

Please let us know about your views in comment section.

Help Others, Please Share..!!!!

                                                     😍..Happy Coding...😍

Comments

  1. why are we doing x^y?

    and whats wrong with this?
    public int hammingDistance(int x, int y) {

    int count=0;
    String a= Integer.toBinaryString(x);
    String b= Integer.toBinaryString(y);

    for(int i=1, j=1;i<a.length() && j<b.length();++i,++j){
    if(a.charAt(i)!=b.charAt(j)){
    count++;
    }
    }

    return count;
    }

    ReplyDelete
  2. Hi,
    Thanks for your valuable question. Reason for doing x^y is given below solution. Still having doubt on use of XOR, check out XOR table in this page and compare with explanation https://en.wikipedia.org/wiki/XOR_gate .
    Also, Integer.toBinaryString() converts int to binary string, but it will automatically all 0's in LHS
    eg) x =1, y = 4 According to your code, it will become a =1 , b = 101 (In a, it eliminates all 0's before 1 but we need 001 for comparison with b = 101). Thus, your code fails in for loop. Hope it clears your doubt. Follow us to receive daily updates from us instantly.

    ReplyDelete

Post a Comment

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits