算法--leetcode 461. Hamming Distance in Python
题目:
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.
两个数的二进制表达式中 对应位不同的位的个数(异或运算)
Python 解决:
主要使用自带库函数,bin()表示将一个数转变为二进制,count(‘1’)计数 1 出现的个数
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count('1')
C++解决:
思路:直接将两数或运算,然后使用exc&=(exc-1)的方式 移除最右边的1,直到循环到exc为0
class Solution { public: int hammingDistance(int x, int y) { int res=0; int exc=x^y; while(exc) { ++res; exc &= (exc - 1); } return res; } };