leetcode with python:461. Hamming Distance

题目:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

给定两数,回传它们的Hamming distance
Hamming distance表两数二进位表示时有几位值不同
ex:1(001)和4(100),它们第一位和第三位值不同,有两位不同
所以它们的Hamming distance为2

这题用到位元运算的概念

class Solution:    def hammingDistance(self, x: int, y: int) -> int:        t=x^y        cnt=0        while t:            if t&1:                cnt=cnt+1            t=t>>1        return cnt

用^运算,两数不同值的位数会以1表示
如1(001)和4(100),会变为5(101)
我们只要计算运算结果的二进位表示有几个1即可
数1的方式类似191.的法一
最后执行时间29ms(faster than 96.03%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章