less than 1 minute read

461. Hamming Distance

문제 링크

https://leetcode.com/problems/hamming-distance/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, return the Hamming distance between them.

제한 사항

  • 0 <= x, y <= 2^31 - 1

입출력 예 #1

  1. Input : x = 1, y = 4
  2. Output : 2
  3. Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.

입출력 예 #2

  1. Input : x = 3, y = 1
  2. Output : 1

문제 풀이

두 수의 XOR 합 결과를 ‘1’의 개수를 센 결과를 출력한다.

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return bin(x ^ y).count('1')

Comments