오늘도 개발

21. Add Binary 본문

자료구조 & 알고리즘/Leetcode

21. Add Binary

Sueeeeeee 2022. 10. 11. 15:03

문제

이진수 string인 a, b의 합을 string으로 반환하시오.

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

 

내가 생각한 방식

a, b를 각각 정수로 변환 후 더함.

더한 결과를 이진수 string으로 변환해서 반환

문제점 : 실행 시간이 오래 걸림

def addBinary(a, b):
    int_a = 0
    int_b = 0

    for i in range(len(a)):
        power = len(a) - i - 1
        int_a += (2 ** power) * int(a[i])
    
    for j in range(len(b)):
        power = len(b) - j - 1
        int_b += (2 ** power) * int(b[j])

    total = int_a + int_b
    result = ''

    while(total > 0):
        result += str(total % 2)
        total = total // 2

    if result == "":
        return "0"

    return result[::-1]

 

다른 해결 방식

파이썬 내장함수 사용.

def addBinary(a, b):
    int_a = int(a, 2) # 2진수를 정수로 변환
    int_b = int(b, 2)
    total = bin(int_a + int_b) # 정수를 2진수로 변환 
    return str(total)[2:]
    
    # return str(bin(int(a, 2) + int (b, 2)))[2:]

자리 올림을 나타내는 carry 변수 사용.

def addBinary(a, b):
    carry = 0
    result = ''

    a = list(a)
    b = list(b)

    while a or b or carry:
        if a:
            carry += int(a.pop())

        if b:
            carry += int(b.pop())

        # carry가 0이면 0을 result에 추가
        # carry가 1이면 1을 result에 추가
        # carry가 2면 0을 result에 추가
        result += str(carry % 2)

        # carry가 0이면 carry는 0이 됨
        # carry가 1이면 carry는 0이 됨
        # carry가 2면 carry는 1이 됨
        carry //= 2

    return result[::-1]

'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글

23. Longest Common Prefix  (0) 2022.10.14
22. Find the Index of the First Occurrence in a String  (0) 2022.10.12
20. Pascal's Triangle  (1) 2022.09.23
19. Spiral Matrix  (1) 2022.09.22
17. Plus One  (0) 2022.09.16