Skip to content

Commit 49f4f7a

Browse files
authored
XOR to get diff; bitCount() or Iterative x &=(x-1)
1 parent 6694efc commit 49f4f7a

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Hamming Distance.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public int hammingDistance(int x, int y) {
3+
return Integer.bitCount(x ^ y);
4+
// return selfBitCount(x, y);
5+
}
6+
7+
public int selfBitCount(int x, int y) {
8+
int dif = x ^ y;
9+
int res = 0;
10+
while(dif > 0) {
11+
dif &= dif - 1;
12+
res++;
13+
}
14+
return res;
15+
}
16+
}

0 commit comments

Comments
 (0)