leetcode 476. Number complement

wonderful world·2021년 12월 27일
0

leetcode

목록 보기
14/21

문자열에서 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
profile
hello wirld

0개의 댓글