알고리즘 스터디

[Leetcode/파이썬]67. Add Binary

난쟁이 개발자 2025. 3. 16. 19:04
반응형

Add Binary

Difficulty: Easy


Given two binary strings a and b, return their sum as a binary string.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 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.
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        decimal_a = decimal_b = 0
        
        for i in range(len(a)) :
            if a[i] == '1' :
                decimal_a += 1 << (len(a) - i - 1)

        for i in range(len(b)) :
            if b[i] == '1' :
                decimal_b += 1 << (len(b) - i - 1)

        print('decimal_a', decimal_a)
        print('decimal_b', decimal_b)

        nums = decimal_a + decimal_b
        res = bin(nums)[2:]
        return res

이 풀이는 일반적인 풀이로, int 메서드 활용법을 잘 모르시는 분들이 이해하기 편한 풀이 방법이다.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        a = int(a, 2)
        b = int(b, 2)

        nums = a + b
        res = bin(nums)[2:]
        return res

이 두 풀이 방법이 일반적인 풀이 인듯 하다.

이진법을 십진법으로 바꿔서 풀이한 후 다시 이진법으로 풀면 쉽게 이 문제를 해결할 수 있을 것이다. 

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        decimal_a = decimal_b = 0
        res = []
        ans = ''
        
        for i in range(len(a)) :
            if a[i] == '1' :
                decimal_a += 1 << (len(a) - i - 1)

        for i in range(len(b)) :
            if b[i] == '1' :
                decimal_b += 1 << (len(b) - i - 1)

        # print('decimal_a', decimal_a)
        # print('decimal_b', decimal_b)

        nums = decimal_a + decimal_b
        # res = bin(nums)[2:]

        while nums != 0 :
            residue = nums % 2
            res.append(str(residue))
            nums //= 2
        ans = ''.join(res[::-1])
        return ans if ans != '' else '0'

스터디 피드백 중 bin 메서드를 사용하지 말고 풀어보라고 하였을 때 어떻게 대처할까를 고민해보았다.

실제로 코딩테스트에서 면접 때 질문이 들어올 수 도 있다는 말에 이런식으로 풀어보는 것도 연습을 자주 해야겠다고 생각했다. 다들 힘냅시다

반응형