汉明距离
题目:
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)
仅仅比较两个数字,转换成二进制字符串,遍历比较。唯一注意的就是将较短的字符串前面加0补足和长的相同位数。
^运算 按位异或 异或运算满足相同为0,不同为1,正好可以将bit位上不同的标为1,结果表示为整数。
利用python内置函数bin转换一个整数x为二进制的字符串表示。
内置函数count() 方法用于统计字符串里某个字符出现的次数。