본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 67. Add Binary

반응형

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:
        dec_a = dec_b = 0

        a = reversed(a)
        b = reversed(b)

        cnt_a = cnt_b = 0

        for i in a :
            i = int(i)
            dec_a += (2 ** cnt_a) * i
            cnt_a += 1

        for i in b :
            i = int(i)
            dec_b += (2 ** cnt_b) * i
            cnt_b += 1

        dec_a += dec_b
        
        return bin(dec_a)[2:]

이진수를 십진수로 바꾸고 두 수를 합한 다음, 다시 이진수로 표현하는 문제이다. 그냥 진행할 경우에는 길이를 하나씩 빼가면서 계산하면 된다. 저는 뒤집은 다음 하나씩 올라가면서 계산함.

반응형