본문 바로가기

00/algorithm

Add Binary (in Python)

반응형

Problem


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:

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

Example 2:

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


Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
 
        # ans = int(a, 2) + int(b, 2)
        # return "{0:b}".format(ans)
 
        a_int = int(a, 2)
        b_int = int(b, 2)
        
        carry = 1
        
        while carry:
            # 1&1=1. carry 쉽게 계산 가능.
            carry = (a_int & b_int) << 1
            #1^1=0^0=0, 1^0=0^1=1
            a_int = a_int ^ b_int
            b_int = carry
            
        return "{0:b}".format(a_int)
cs


Source 

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


반응형

'0 > algorithm' 카테고리의 다른 글

Minimum Increment to Make Array Unique (in Python)  (0) 2019.01.25
Climbing Stairs (in Python)  (0) 2019.01.23
Rotate Image (in Python)  (0) 2019.01.23
Permutations (in Python)  (0) 2019.01.23
Spiral Matrix (in Python)  (0) 2019.01.23