Posts

Showing posts with the label Hamming Distance

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. Note: 0 ≤ x , y < 2 31 . Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.   class Solution {     public int hammingDistance(int x, int y) {         String str = Integer.toBinaryString(x^y);         return str.replaceAll("0","").length();     } } Try it on Leetcode Here, we are going to solve in more easiest way. The hint hidden in this problem is, we need to convert integer to binary and compare both for any differences in 1's position. 1) Do XOR for both numbers.(XOR of same digits (0, 1) will be same). From this, we get difference in 1's position, but it will be in int type. 2) Convert int to binary using toBinaryString(). 3) R