반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 476 | Number Complement | Python 본문
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
반응형
'스터디 > 코테' 카테고리의 다른 글
[백준] 2638번 | 치즈 | (0) | 2021.12.27 |
---|---|
[LeetCode] 56 | Merge Intervals | Python (0) | 2021.12.27 |
[백준] 2636번 | 치즈 | C++ (0) | 2021.12.23 |
[LeetCode] 210 | Course Schedule II | Python (0) | 2021.12.23 |
[백준] 2583번 | 영역 구하기 | C++ (0) | 2021.12.22 |
Comments