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 ≤ x
, y
<
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() 方法用于统计字符串里某个字符出现的次数。