Problem
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.
Solution: Bit Operation
Time complexity: O(logn)
Space complexity: O(1)
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Running time: 6 ms class Solution { public: int hammingDistance(int x, int y) { int ans = 0; int t = x^y; while (t) { ans += t & 1; t >>=1; } return ans; } }; |
|
1 2 3 4 5 6 7 8 |
// Author: Huahua // Running time: 9 ms class Solution { public: int hammingDistance(int x, int y) { return __builtin_popcount(x ^ y); } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.


Be First to Comment