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

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

LeetCode - Swap Nodes in Pairs Solution - The Coding Shala

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala