题目:
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%)
那我们下题见