calculate the Hamming distance for two given integers

Problem

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:
Input: x = 8, y = 1

Output: 2

Explanation:

number    bits
8 1 0 0 0
1 0 0 0 1

Solution

With Java it is quite easy to calculate. First we will do a bitwise XOR and then use Integer.bitCount() to calculate the number of one-bits in the two’s complement binary representation of XORed value.

package com.programtalk.learn.interview.questions;
public class HammingDistance {
	
	public static void main(String[] args) {
		System.out.println(hammingDistance(8, 1));
	}
    public static int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

Like this post? Don’t forget to share it!