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.

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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