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.
Code
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xb = self.int2b(x)
yb = self.int2b(y)
lenx = len(xb)
leny = len(yb)
i = res = 0
while i < lenx or i < leny:
if i >= lenx:
if yb[leny - i - 1] != '0':
res += 1
elif i >= leny:
if xb[lenx - i - 1] != '0':
res += 1
elif xb[lenx - i - 1] != yb[leny - i - 1]:
res += 1
i += 1
return res
def int2b(self, num):
if num <= 1:
return str(num)
else:
return self.int2b(num / 2) + str(num % 2)
看到这道题还是觉得小开心的,因为其中关于十进制转二进制的算法是当初大一做作业时遇到的问题,这是当时想到的算法,现在觉得也是很精练,也算是把这算法铭记于心了。十进制转二进制了,剩下的就是从后往前遍历俩字符串了。
看了下别人的算法,果然使用位操作,感觉很6,学习学习。
Code(pengr7)
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
下面是代码的解释:
Considering this example. Let’s say n = 10101, and dist = 0 asccording to above code of @pengr7.
Before we go into the while loop. n = 10101, dist = 0
Loop 1. dist = 1, n =10101 & 10100 = 10100
Loop 2. dist = 2, n =10100 & 10011 = 10000
Loop 3. dist = 3, n =10000 & (0)1111 = 0
Loop ends. dist = 3
The change of n :
10101
10100
10000
00000
Conclusion: n & (n-1) converts the right most 1 to 0 .
This is the key idea solving the problem. By counting how many times we can perform this operation, we know how many 1 exists in the binary representation of n
这个方法妙在可以直接将最右位的1变为0,减少遍历的次数。还有一种算法:
class Solution(object):
def hammingDistance(self, x, y):
z = x ^ y
count = 0
while z > 0:
count += z & 1
z >>= 1
return count
这算法稍微偷懒,每次只判断最右位是否为1,然后右移一位,遍历次数比上面的算法会稍微多些。
两种算法都学习学习。
Code
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
res = x ^ y
cnt = 0
while res:
cnt += 1
res = res & (res - 1)
return cnt
照着学了下
Conclusion
关于位操作,平常基本没有接触,这次学到了些东西