본문 바로가기
알고리즘/LeetCode

[LeetCode] Add Binary

by Tsoo 2020. 7. 20.

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

 

Example 1:

Input: a = "11", b = "1" Output: "100"

 

Example 2:

Input: a = "1010", b = "1011" Output: "10101"

 

Constraints:

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4
  • Each string is either "0" or doesn't contain any leading zero.

Solution

1. binary함수를 이용해 더하면 재미가 없으므로 직접 구현해보기로한다.

2. 입력받는 두 수 a,b의 길이로 최대값을 구한후 그 값으로 반복문을 돌린다. 길이가 작은수는 앞에 '0'으로 채워준다.

3. 뒤에서부터 반복문을 돌리고 자리수를 더해가는데, idx를 통해 각 자리수의 합이 2가 넘는경우 idx를 1로주고 다음자리수에 더해간다.

4. 마지막에 idx가 남아있는 경우 처리까지 끝낸다.

#(3) Add Binary

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        end = max(len(a),len(b))
        a = '0'*(end-len(a))+a
        b = '0'*(end-len(b))+b
        result = ''
        idx = 0
        for i in range(end-1,-1,-1):
            tmp = 0
            if int(a[i]) + int(b[i]) + idx ==2:
                idx = 1
                result = '0'+result
            elif int(a[i]) + int(b[i]) + idx == 3:
                idx = 1
                result = '1'+result
            else:
                result = str(int(a[i])+int(b[i])+idx) + result
                idx = 0
        if idx:
            result = '1'+result
        return result

댓글