(LeetCode) 461. Hamming Distance
461. Hamming Distance
- Explore : Interview > Top Interveiw Questions > Easy Collection
- 분류 : Others
- 난이도 : Easy
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
, return the Hamming distance between them.
Example 1
1 2 3 4 5 6 7
| 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.
|
Example 2
1 2
| Input: x = 3, y = 1 Output: 1
|
Constraints
Solution
Exapnder
1 2 3
| class Solution { fun hammingDistance(x: Int, y: Int): Int = Integer.toBinaryString(x xor y).count { it == '1' } }
|
Point of Thinking
- 주어진
x
와 y
를 xor 연산 한 뒤 1비트만 세어주면 Accepted.