작심삼일

[LeetCode] 476 | Number Complement | Python 본문

스터디/코테

[LeetCode] 476 | Number Complement | Python

yun_s 2021. 12. 27. 09:21
728x90
반응형

문제 링크: https://leetcode.com/problems/number-complement/


문제

The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

  • For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

Given an integer num, return its complement.


조건

  • 1 <= num < $2^{31}$

내 풀이

2로 나눈 후의 나머지가 0일 때만 더해서 계산하는 간단한 문제다.


코드

class Solution:
    def findComplement(self, num: int) -> int:
        ans = 0
        cur = 1
        
        while num > 1:
            a, b = num//2, num%2
            num = a
            if b == 0:
                ans += cur
            cur *= 2
        
        return ans
728x90
반응형
Comments