Leetcode 461. Hamming Distance

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Hamming Distance

2. Solution

  • 32 times
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int hammingDistance(int x, int y) {
int m = x ^ y;
int distance = 0;
while(m) {
distance += m & 1;
m = m >> 1;
}
return distance;
}
};
  • n times(n is the number of 1)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Solution {
    public:
    int hammingDistance(int x, int y) {
    int m = x ^ y;
    int distance = 0;
    while(m) {
    m = m & (m - 1);
    distance++;
    }
    return distance;
    }
    };

Reference

  1. https://leetcode.com/problems/hamming-distance/description/
如果有收获,可以请我喝杯咖啡!