반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 67 | Add Binary | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/add-binary/
문제
Given two binary strings a and b, return their sum as a binary string.
조건
- 1 <= a.length, b.length <= 104
- a and b consist only of '0' or '1' characters.
- Each string does not contain leading zeros except for the zero itself.
내 풀이
맨 뒷자리부터 덧셈을 하기위해 a와 b를 역으로 적은 Ra, Ra를 만든다.
자릿수를 맞춰주기 위해 뒤에 0을 추가한다.
각 자리별로 더한 후 올림이 필요한 것은 t를 이용한다.
코드
class Solution:
def addBinary(self, a: str, b: str) -> str:
Ra, Rb = a[::-1], b[::-1]
ans = ''
Na, Nb = len(Ra), len(Rb)
if Na > Nb:
Rb += '0' * (Na-Nb)
elif Nb > Na:
Ra += '0' * (Nb-Na)
t = 0
for ta, tb in zip(Ra, Rb):
s = t + int(ta) + int(tb)
if s == 0:
ans += '0'
t = 0
elif s == 1:
ans += '1'
t = 0
elif s == 2:
ans += '0'
t = 1
elif s == 3:
ans += '1'
t = 1
ans += str(t)
if ans[-1] == '0': return ans[-2::-1]
else: return ans[::-1]
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 452 | Minimum Number of Arrows to Burst Balloons | Python (0) | 2022.01.13 |
---|---|
[LeetCode] 701 | Insert into a Binary Search Tree | Python (0) | 2022.01.12 |
[LeetCode] 1094 | Car Pooling | Python (0) | 2022.01.06 |
[LeetCode] 131 | Palindrome Partitioning | Python (0) | 2022.01.05 |
[LeetCode] 1009 | Complement of Base 10 Integer | Python (0) | 2022.01.04 |
Comments