Hamming Distance - The Coding Shala

Home >> Programming >> Hamming Distance

 In this post, we will learn how to find Hamming Distance between two integers and will implement its solution in Java.

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.

Example 1:
Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)

Hamming Distance Java Program

Approach 1

First find the XOR or both number then check bits, if 1 than increase count by 1.

Java Program: 

class Solution {
    public int hammingDistance(int x, int y) {
        x = x ^ y;
        int dis = 0;
        for(int i=0; i<32; i++) {
            if(((x >> i) & 1) == 1) dis++;
        }
        return dis;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala