67_Add Binary

1 minute read

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:

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

Example 2:

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

easy 난이도 문제

input_value[::-1] 로 스트링을 reverse 할 수도 있다.

그러나,

1
2
for idx, b in reversed(list(enumerate(input_value))):
    pass

위와 같이 사용도 가능하다.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        
        def binaryToDecimal(input_value):
            final_decimal = 0
            for idx, b in enumerate(input_value[::-1]):
                
                if b == "1":
                    final_decimal += pow(2,idx)
            return final_decimal
        
        def decimalToBinary(input_value):
            p_jesoo   = input_value
            jesoo = 2
            
            binary_string = ""
            while p_jesoo != 1:
            
                if p_jesoo % jesoo == 0:
                    binary_string += "0"
                
                else:
                    binary_string += "1"
                              
                p_jesoo /= jesoo
                #print(jesoo)
            binary_string += "1"
            return binary_string[::-1]
        
        if a=="0" and b=="0":
            return "0"
        
        plus_decimal = binaryToDecimal(b) + binaryToDecimal(a)
        
        final_binary = decimalToBinary(plus_decimal)
        
        return final_binary