461.汉明距离

题目描述:

image.png


解:

做法有三种:

  1. 暴力的遍历32位统计有几位不一样的(可以先异或,再判断异或后的值每一位是否为0)

    1. class Solution {
    2. public int hammingDistance(int x, int y) {
    3. int ret = 0;
    4. int tmp = x ^ y;
    5. for(int i=0; i<32; i++) {
    6. ret += (tmp & 1) == 0 ? 0 : 1;
    7. tmp >>= 1;
    8. }
    9. return ret;
    10. }
    11. }
  2. 通过 x & (x - 1) 直接获取二进制位中最右边1的性质优化

    1. class Solution {
    2. public int hammingDistance(int x, int y) {
    3. int ret = 0;
    4. int tmp = x ^ y;
    5. while (tmp != 0) {
    6. tmp = tmp & (tmp - 1);
    7. ret ++;
    8. }
    9. return ret;
    10. }
    11. }
  3. 使用语言自带的功能函数。

    1. class Solution {
    2. public int hammingDistance(int x, int y) {
    3. return Integer.bitCount(x ^ y);
    4. }
    5. }