1. Description
The Hamming distance between two integers is the number of positions at which the corresponding bits are differnt. Given two integer x and y, return the Hamming distance between them.
constraints :
- 0 <= x, y <= \(2^{31}\) - 1
2. Algorithms
Logical operator XOR returns 1 when corresponding bits are different. After we apply XOR between x and y, we just return counts of "1".
- Start
- Apply XOR operator(^) between x and y.
- Change result of logical operation into bit representation.
- Count "1" in binary representations and return result.
- End
3. Codes
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count("1")
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
476 Number Complement (0) | 2022.08.31 |
---|---|
463 Island Perimeter (0) | 2022.08.31 |
459 Repeated Substring Pattern (0) | 2022.08.30 |
455 Assign Cookies (0) | 2022.08.30 |
448 Find All Numbers Disappeared in an Array (0) | 2022.08.30 |