forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHamming Distance.java
More file actions
46 lines (40 loc) · 1.15 KB
/
Hamming Distance.java
File metadata and controls
46 lines (40 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public int hammingDistance(int x, int y) {
return findCount(x,y);
}
public int findCount(int x, int y) {
StringBuilder sbX = new StringBuilder("");
StringBuilder sbY = new StringBuilder("");
while (x>0) {
sbX.append(String.valueOf(x%2));
x /= 2;
}
while (y>0) {
sbY.append(String.valueOf(y%2));
y /= 2;
}
String binX = sbX.reverse().toString();
String binY = sbY.reverse().toString();
if (binX.length() > binY.length()) {
int d = binX.length() - binY.length();
while (d>0) {
binY = "0" + binY;
d--;
}
}
else if (binX.length() < binY.length()) {
int d = binY.length() - binX.length();
while (d>0) {
binX = "0" + binX;
d--;
}
}
int count = 0;
for (int i=0;i<binX.length();i++) {
if (binX.charAt(i) != binY.charAt(i)) {
count++;
}
}
return count;
}
}