본문 바로가기
Algorithm

[Bit Operation] 비트연산

by YGSEO 2021. 4. 14.
728x90

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 문제 (link)

 

def findTheDifference3(self, s, t):
        return chr(reduce(operator.xor, map(ord, s + t)))

이 부분을 풀어보자.

 

chr

인자로 int(Unicode code point)를 받고 string을 return 한다.(link)

 

from functools import reduce (link)

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

 

 

 


비트연산 위키피디아: ko.wikipedia.org/wiki/%EB%B9%84%ED%8A%B8_%EC%97%B0%EC%82%B0

728x90

댓글