본문 바로가기
Leetcode

[LeetCode] Hamming Distance 파이썬 (bitwise)

by YGSEO 2021. 4. 19.
728x90

 

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        distance = 0
        z = x ^ y
        while z:
            distance += 1
            z &= z - 1
        return distance

    def hammingDistance2(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count('1')

2번째 솔루션

비트 XOR 연산으로 position이 서로 다른지 확인한다.

x = 1, y = 4일 경우

001

XOR

100

= 101

이 str에서 count메서드를 사용해서 1의 횟수를 return

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/hamming-distance.py

728x90

댓글