calculate the Hamming distance for two given integers


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.

Input: x = 8, y = 1

Output: 2


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


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);

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.