본문 바로가기

xor3

[LeetCode] Hamming Distance 파이썬 (bitwise) 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의 횟수를 retur.. 2021. 4. 19.
[Bit Operation] 비트연산 NOT 연산은 각 자릿수의 값을 반대로 바꾸는 연산이다. NOT 0111 = 1000 OR 연산은 두 값의 각 자릿수를 비교해, 둘 중 하나라도 1이 있다면 1을, 아니면 0을 계산한다. 0101 OR 0011 = 0111 XOR 연산은 두 값의 각 자릿수를 비교해, 값이 같으면 0, 다르면 1을 계산한다. 0101 XOR 0011 = 0110 AND 연산은 두 값의 각 자릿수를 비교해, 두 값 모두에 1이 있을 때에만 1을, 나머지 경우에는 0을 계산한다. 0101 AND 0011 = 0001 XOR 연산을 많이 봤는데 XOR 연산이 0으로만 된 bit를 return 한다면 같은 숫자(?)라는 것을 의미하고 아니라면 다르다는 것을 알 수 있다. [LeetCode] Find the Difference 문.. 2021. 4. 14.
[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: if len(s) == 0: return t # s = "" S = Counter(s) T = Counter(t) T.subtract(S) # inplace res = [k for k, v in T.items() if v > 0] return res[0] Counter 클래스에는 subtract라는 메서드가 있다. inplace이기 때문에 이 점을 유의할 것. 다른 풀이들 class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str.. 2021. 4. 14.