[LeetCode] 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
, 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.
两个数字之间的汉明距离是其二进制数对应位不同的个数,两个数异或,把为1的数量累加起来就是汉明距离。
Java:
1 2 3 4 5 6 7 8 9 10 | public int hammingDistance( int x, int y) { int res = x ^ y; int count = 0 ; for ( int i = 0 ; i < 32 ; i++) { if ((res & 1 ) != 0 ) count++; res >>= 1 ; } return count; } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution( object ): def hammingDistance( self , x, y): """ :type x: int :type y: int :rtype: int """ distance = 0 z = x ^ y while z: distance + = 1 z & = z - 1 return distance |
Python:
1 2 3 4 5 6 7 8 | class Solution( object ): def hammingDistance( self , x, y): """ :type x: int :type y: int :rtype: int """ return bin (x ^ y).count( '1' ) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public : int hammingDistance( int x, int y) { int res = 0; for ( int i = 0; i < 32; ++i) { if ((x & (1 << i)) ^ (y & (1 << i))) { ++res; } } return res; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : int hammingDistance( int x, int y) { int res = 0, exc = x ^ y; while (exc) { ++res; exc &= (exc - 1); } return res; } }; |
C++:
1 2 3 4 5 6 7 | class Solution { public : int hammingDistance( int x, int y) { if ((x ^ y) == 0) return 0; return (x ^ y) % 2 + hammingDistance(x / 2, y / 2); } }; |
类似题目:
[LeetCode] 191. Number of 1 Bits 二进制数1的个数
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步