작심삼일

[LeetCode] 67 | Add Binary | Python 본문

스터디/코테

[LeetCode] 67 | Add Binary | Python

yun_s 2022. 1. 10. 10:40
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
반응형
Comments