반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 1009 | Complement of Base 10 Integer | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/complement-of-base-10-integer/
문제
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 n, return its complement.
조건
- 0 <= n < $10^9$
내 풀이
LeetCode 476번(Number Complement)와 같은 문제다.
다만 조건에서 n이 0부터 시작한다는 점이 다르다.
따라서 n=0일 때 1을 출력하는 것을 추가한다.
코드
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0: return 1
ans = 0
cur = 1
while n > 1:
a, b = n//2, n%2
n = a
if b == 0:
ans += cur
cur *= 2
return ans
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 1094 | Car Pooling | Python (0) | 2022.01.06 |
---|---|
[LeetCode] 131 | Palindrome Partitioning | Python (0) | 2022.01.05 |
[LeetCode] 997 | Find the Town Judge | Python (0) | 2022.01.03 |
[LeetCode] 1015 | Smallest Integer Divisible by K | Python (0) | 2021.12.30 |
[LeetCode] 116 | Populating Next Right Pointers in Each Node | Python (0) | 2021.12.29 |
Comments