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
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.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala