Hamming Distance - The Coding Shala
Home >> Programming >> Hamming Distance
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.
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
Explanation:
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; } }
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment