问题链接:https://leetcode.com/problems/hamming-distance/#/description
The 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 < 2^31.
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. Subscribe to see which companies asked this question.一开始想的是两个数异或,然后把异或出来的结果转成二进制的字符串(”01001”这样),然后数1的个数。后来觉得用位操作肯定更快啊,就准备这样写:
public class Solution { public int hammingDistance(int x, int y) { // 思路弄一个int当掩码, // 从0x01到0x80 // 每次左移一位去跟两个数与,如果结果不一样就加1 int mask = 0x01; int count = 0; while (mask <= 0x80){ if((x & mask) != (y & mask)){ count ++; } mask <<= 1; } return count; } }我把一个16进制记成16位了,当然结果是没有通过。我仔细想了想,觉得知道问题在于位数了,所有改成了下面这样:
public class Solution { public int hammingDistance(int x, int y) { // 思路弄一个int当掩码, // 从0x00000001到0x80000000 // 每次左移一位去跟两个数与,如果结果不一样就加1 int mask = 0x00000001; int count = 0; while (mask <= 0x80000000){ if((x & mask) != (y & mask)){ count ++; } mask <<= 1; } return count; } }这样了以后连1,4的测试用例都过不了了,我觉得很奇怪啊,凭什么啊。我怀疑是那个提交的系统出错了,就在IDE上试了试(嗯,没错,作弊了),确实是过不了。用IDE调试,发现0x80000000就是个负数。终于想起来符号位的事。改了过来。
修改以后过了。可是运行速度只超过了5%的Java代码,再去评论区好好学习一个。
来,见识一下大神们的风采。只能说大写的服!
https://discuss.leetcode.com/topic/72093/java-1-line-solution-d
public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } }各种bitCount,来好好学习一个。https://tech.liuchao.me/2016/11/count-bits-of-integer/
n & (n – 1) will clear the last significant bit set, e.g. n = 112
n | 1 1 1 0 0 0 0 n - 1 | 1 1 0 1 1 1 1 n &= n - 1 | 1 1 0 0 0 0 0 --------------------------- n | 1 1 0 0 0 0 0 n - 1 | 1 0 1 1 1 1 1 n &= n - 1 | 1 0 0 0 0 0 0 --------------------------- n | 1 0 0 0 0 0 0 n - 1 | 0 1 1 1 1 1 1 n &= n - 1 | 0 0 0 0 0 0 0Hence loop will go through as many iterations as there are set bits, and when n becomes zero, count is exactly the answer.
int bitCount(int n) { int count = 0; while (n != 0) { n &= n - 1; count++; } return count; }https://discuss.leetcode.com/topic/72089/java-3-line-solution
public int hammingDistance(int x, int y) { int xor = x ^ y, count = 0; for (int i=0;i<32;i++) count += (xor >> i) & 1; return count; }嗯,LeetCode值得好好刷刷。