Java 1 Line Solution :D

• What does come to your mind first when you see this sentence `"corresponding bits are different"`? Yes, `XOR`! Also, do not forget there is a decent function Java provided: `Integer.bitCount()` ~~~

``````public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
``````

• haha, that builtin function is mind blown

• and here are several ways of impl bitCount():

count-bits-of-integer

Enjoy :-P

• @liupangzi wooo, that post is nice, thanks!

• bu yao zuo bi, da xiong di.

• This was awesome. Built-in java implementation from Hacker's Delight!

• That was really awesome!

• ……我果然迷失在人生的道路上了。

• it acturelly a quickly method! u have such a good memery

• pretty cool code.
Learning distance.
JAVA API killer!

• @shawngao Wow...........

• shawngao Do you mind explain what the line of code does? I'm not sure how the logic works there

• @JohPa8696 Per the problem: The Hamming distance (https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.

`XOR` can help you find out at what positions bits are different. i.e. 1001 ^ 0111 = 1110.

Then things left is to count how many `1` in above result. `Integer.bitCount()` can help you do that.

• @shawngao Thank you so much. Great explanation!

• @shawngao nice

• zhe dou keyi

• @shawngao nice solution!

• @USCMaverick wo fu ni!:)

• I love this solution as it would be a nice way to do in real software development. However, it it actually not an ending point of the problem in an interview. You may tell this solution to the interviewes first to show that you are able to come up with a working solution fast (and also your familiarity with Java). However, the interviewer is then going to ask you how `Integer.bitCount()` does it for you. That is when @liupangzi's suggested post comes to use, and leads to deeper discussions.

• awesome!!! I feel myself stupid

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.