Hamming Distance
1. Title
461. Hamming Distance
2. Http address
https://leetcode.com/problems/hamming-distance/?tab=Description
3. The question
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 < 231.
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.
4. Code
public class Solution { public int hammingDistance(int x, int y) { String xbits = Integer.toBinaryString(x); String ybits = Integer.toBinaryString(y); int lenX = xbits.length(); int lenY = ybits.length(); int re = 0, i = 0, j = 0; if (lenX > lenY) { for (i = 0; i < lenX - lenY; i++) { if (xbits.charAt(i) != '0') { re++; } } } else { for (j = 0; j < lenY - lenX; j++) { if (ybits.charAt(j) != '0') { re++; } } } while (i < lenX && j < lenY) { if (xbits.charAt(i++) != ybits.charAt(j++)) { re++; } } return re; } }
浙公网安备 33010602011771号