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 find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala