Post

leetcode(리트코드)-67 Add Binary(python)

leetcode 67 - Add Binary 문제입니다.

1. 문제

https://leetcode.com/problems/add-binary/


2. Input , Output


3. 분류 및 난이도

Eazy 난이도 문제입니다.
Top Interview 문제입니다.


4. 문제 해석

  • 문자열로 들어온 숫자를 binary로 표현되었다고 생각하고 두 숫자를 더한 binary string을 리턴합니다.

5. code

코드설명

python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i = len(a)-1
        j = len(b)-1
        carry = 0
        num = 0
        res = ""
        while i >=0 and j >=0 :
            sum = int(a[i]) + int(b[j]) + carry
            carry = int(sum) //2
            num = int(sum)%2
            res +=str(num)
            i-=1
            j-=1
        while i>=0 : 
            sum = int(a[i]) + carry
            carry = int(sum) //2
            num = int(sum)%2
            res +=str(num)
            i-=1
        while j>=0:
            sum = int(b[j]) + carry
            carry = int(sum) //2
            num = int(sum)%2
            res +=str(num)
            j-=1
        if carry ==1:
            res+="1"
        return res[::-1]

6. 결과 및 후기, 개선점

필요시 c++로 짜드리겠습니다.

This post is licensed under CC BY 4.0 by the author.