(Medium) Hamming Distance LeetCode
Description:
he 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.
Solution
class Solution { public int hammingDistance(int x, int y) { String A = GetBit(x); String B = GetBit(y); int a = A.length(); int b = B.length(); int bigger = a>b? a:b; int smaller = a>b? b:a; int result = 0; if(a>b){ for(int i = 0; i<smaller;i++){ if(A.charAt(i)!= B.charAt(i)){ result++; } } for(int i = smaller;i<bigger; i++){ if(A.charAt(i)!='0'){ result++; } } } else{ for(int i = 0; i<smaller;i++){ if(A.charAt(i)!= B.charAt(i)){ result++; } } for(int i = smaller;i<bigger; i++){ if(B.charAt(i)!='0'){ result++; } } } return result; } public String GetBit(int N){ String res = ""; int remain = N; do { int bit = remain%2; remain = remain/2; res = res +bit; } while (remain>0); return res; } }

浙公网安备 33010602011771号