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:
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.
代码:
python
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
补知识:
1、Python内置函数:bin()、oct()、int()、hex()分别可以将integer number转化为二、八、十、十六进制的string,且分别带有0b、0o、0x前缀。这用 bin(10)[2:]
可以得到除前辍后的字符串。通过嵌套使用可以做进制之间的转化,例如 bin(int(oct(10)))
可以将十进制的10转化为八进制的数,然后再转十进制的数,最后转二进制的数,这里不用去掉前辍,但是最后print出来的会带有二进制的前缀。
2、python内置函数:str.count(sub, start= 0,end=len(string)) ,sub是子字符串,可以计算得到子字符串出现的数目。
java
public class Solution {
public int hammingDistance(int x, int y) {
int sum = 0;
for(int i = 0; i < 32; i++) {
int bitx = (x >> i) & 1;
int bity = (y >> i) & 1;
sum += (bitx + bity) & 1;
}
return sum;
}
}
public class Solution {
public int hammingDistance(int x, int y) {
int z = x ^ y;
int cnt = 0;
while(z != 0){
if((z & 1) == 1){
cnt ++;
}
z = z >> 1;
}
return cnt;
}
}
参考资料:
1、http://www.jb51.net/article/32927.htm 2017.8.3
2、http://www.runoob.com/python/att-string-count.html 2017.8.3
3、http://www.xuebuyuan.com/1416450.html?mobile=1 2017.8.3