Leetcode学习(4)—— Hamming Distance

来源:互联网 发布:qq企业邮箱端口号 编辑:程序博客网 时间:2024/06/06 09:00

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.


Hamming 距离是两个整数对应的 位 bit 不相同的数量之和。
给出两个数 x ,y,计算他们之间的 Hamming 距离。


Note:
0 ≤ x, y < 2^31.

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.

思路:将给出两的两个十进制数转换成二进制数,计算他们长度的差值,将长度小的数用 0 补齐,依次比较他们的每一位,每当遇到不相同的位时,计数器+1

class Solution(object):    def hammingDistance(self, x, y):        bin_x = bin(x)[2:]        bin_y = bin(y)[2:]        nums = abs(len(bin_y) - len(bin_x))        if len(bin_x) > len(bin_y):            for i in range(nums):                bin_y = '0' + bin_y        else:            for i in range(nums):                bin_x = '0' + bin_x        # print(bin_x)        # print(bin_y)        count = 0        for i in range(max(len(bin_x), len(bin_y))):            # print(i)            # print(bin_x[-i], bin_y[-i])            if bin_x[i] != bin_y[i]:                count += 1        return count
0 0
原创粉丝点击