Hamming distance between two Integers in Java.
Given two integers, find the hamming distance between them.
Hamming Distance: hamming distance is the count of bits that are different at same position in a binary representation of two numbers.
Lets understand what is the input and the expected output.
Algorithm
Note: XOR operation on two numbers: for same bit, it gives 0. for different bit it gives 1.
Step 1: First we XOR both numbers which will give us number which represent bits that are different in both numbers.
number1 = 1
number2 = 15;
number = 1^15 =
0 0 0 1
^ 1 1 1 1
--------------
1 1 1 0 = for same bit in both number, result will be 0, for different bit result will be 1.
Step 2: Count the number of bits that are set in result we got in step 1 and done. Detailed post on counting number of set bits in Integer
Hamming distance between two Integers in Java
package com.javabypatel.misc; class HammingDistance { private static int hammingDistance(int number1, int number2) { int number = number1 ^ number2; int countOfSetBits = 0; while (number != 0) { countOfSetBits += number & 1; number = number >> 1; } return countOfSetBits; } public static void main(String[] args) { int number1 = 1, number2 = 15; System.out.println(hammingDistance(number1, number2)); } }
You may also like to see
Sort Linked list using Merge sort
Bubble Sort
Heap Sort
Selection Sort
Insertion Sort
How ConcurrentHashMap works and ConcurrentHashMap interview questions
How Much Water Can A Bar Graph with different heights can Hold
Interview Questions-Answer Bank
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment