leetcode python 461

Hamming Distance  是指两个字符串之间的汉明距离是指两个相等长度的字符串,对应位置上不同字符的个数。

  例如:

    The Hamming distance between 1011101 and 1001001 is 2. 
    The Hamming distance between 2143896 and 2233796 is 3. 
    The Hamming distance between "toned" and "roses" is 3. 
    1011101 与 1001001 之间的汉明距离是 2。
    2143896 与 2233796 之间的汉明距离是 3。
    "toned" 与 "roses" 之间的汉明距离是 3。

应用十进制转换成二进制的方法解决该问题。

讲解Python主函数什么时候用

http://www.360doc.com/content/14/1023/17/3200886_419259481.shtml

python 整除运算符 //


Problem Statement

(Source) 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 ≤ xy <  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 Solution

^运算 按位异或 异或运算满足相同为0,不同为1,正好可以将bit位上不同的标为1,结果表示为整数。
利用python内置函数bin 转换一个整数 x 为二进制的字符串表示。
内置函数count() 方法用于统计字符串里某个字符出现的次数。
class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count('1')




class Solution(object):
    def hammingDistance(self, x, y):
        dis = 0
        ix = 0
        iy = 0
        xy = 0
        s = []
        sy = []
        for iix in range(1, 32):  
            s.append(0)
        for iiy in range(1, 32):
            sy.append(0)
        while x !=  0:
            s[ix] = x%2
            ix = ix + 1
            x= x // 2
        while y !=  0:
            sy[iy] = y%2
            iy = iy + 1
            y = y // 2    
        for xyy in range(1, 32):
            if s[xy] != sy[xy]:
                dis = dis + 1
            xy = xy + 1 
        return dis  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值