Problem
My Attempt
Brainstorming
I don't know Hamming distance. I don't know java bit operation.
what I can think is that >> two numbers and check one by one.
Result code
fail
Study
Hamming distance : Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
"karolin" and "kathrin" is 3.
"karolin" and "kerstin" is 3.
"kathrin" and "kerstin" is 4.
0000 and 1111 is 4.
2173896 and 2233796 is 3.
Thus, question want to count two bit numbers not same.
xor gate
0^0=0
0^1=1
1^0=1
1^1=0
xor will make 1's what need to count. and count 1's will be answer.
Solution (time, space)
O(n), O(n)
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}