관리 메뉴

솜씨좋은장씨

[leetCode] 476. Number Complement (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 476. Number Complement (Python)

솜씨좋은장씨 2021. 1. 27. 00:07
728x90
반응형

Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.

 

Example 1:

Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Constraints:

Solution

class Solution:
    def findComplement(self, num: int) -> int:
        return int("".join([str(1-int(num)) for num in bin(num)[2:]]), 2)

Solution 풀이

먼저 입력받은 num을 bin을 활용하여 이진수로 변경하고 변경한 다음에 3번째 인자부터 남겨둡니다.

그렇게 만든 숫자에서 한자리씩 가져와 1을 뺀 숫자를 남겨두고 이를 다시 int를 활용해 10진수로 변환해줍니다.

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments