Hamming Distance
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
< 231.
Example:
1 | Input: x = 1, y = 4 |
思路:利用转换二进制的函数,并将两个字符串相差的位置补0,最后统计有多少位不同的即可。
代码如下:
1 | class Solution { |
还有一种按位亦或的算法,将两个输入的数字做按位异或,再统计得到的结果中1的个数就是这两个数的海明距离。
1 | class Solution { |