Hamming Distance – LeetCode 461
Problem
Description
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 < 2^{31}.$
Answer
Original
Code
1 | class Solution { |
思路
直接亦或然后数设置的位数,这里用位操作。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$5$ ms,排名$76.27\%$
Better
思路
使用bitset数数。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$4$ ms,排名$76.27\%$
Code
1 | class Solution { |