用了很多笨方法的感觉
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ xlist = [] ylist = [] while(True): xlist.append(x%2) x/=2 if x==0: break while(True): ylist.append(y%2) y/=2 if y==0: break cnt = 0 if len(ylist)>len(xlist): lenth = len(xlist) cntt = ylist[lenth:].count(0) else: lenth = len(ylist) cntt = xlist[lenth:].count(0) for i in range(lenth): if ylist[i]!=xlist[i]: cnt += 1 return cnt+abs(len(ylist)-len(xlist))-cntt
38ms 38.43%
----------------------------------
果然看discuss喷出一口老血
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count('1')
33ms 95.17%
学习bin()函数。返回int类型的二进制表示法,返回类型为string,骚气的是注意前面有'0b'
比如bin(10)为‘0b1010’
比如bin(10).count('b') 为1
---------------------------------
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x = x ^ y y = 0 while x: y += 1 x = x & (x - 1) return y33ms 95.17% (这个号称beat 100%,可能在他那个时候吧。。)