소프트웨어에 대한 모든 것

LeetCode 풀기 - 476. Number Complement 본문

카테고리 없음

LeetCode 풀기 - 476. Number Complement

앤테바 2021. 12. 27. 21:12
반응형

476. Number Complement

https://leetcode.com/problems/number-complement/

 

Number Complement - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

class Solution:
    def findComplement(self, num: int) -> int:
        res = []
        for c in bin(num)[2:]:
            if c == '1':
                res.append('0')
            else:
                res.append('1')
        return int(''.join(res), base=2)

솔루션2)

class Solution:
    def findComplement(self, num: int) -> int:
        # ex) 101 ^ 111 = 010
        mask = '1' * len(bin(num)[2:])
        return int(mask, base=2) ^ num

 

반응형
Comments