문자열에서 0 -> 1, 1 -> 0 으로 바꾼 후 다시 숫자로 변환. 그닥 효율이 좋진 않음.
class Solution:
def findComplement(self, num: int) -> int:
bits = bin(num)[2:]
bits_comp = ''.join([{'0': '1', '1': '0'}[b] for b in bits])
return int(bits_comp, 2)
다시 풀기.
def findComplement(self, num: int) -> int:
r = 0
shift = 0
while num != 0:
bit = num % 2
bit = (not bit) << shift
r |= bit
num >>= 1
shift += 1
return r