卖萌的弱渣

I am stupid, I am hungry.

Add Binary

Given two binary strings, return their sum (also a binary string).

Example,

1
2
3
a = "11"
b = "1"
Return "100".

Solution

(Add-Binary.py) download
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
 class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if a == None:
            return b
        if b== None:
            return a

        ret = ""
        add = 0
        i = len(a)-1
        j = len(b)-1

        while i >= 0 and j >= 0:
            l = int(a[i])
            r = int(b[j])
            ret = str((l+r+add)%2)+ret
            add = (l+r+add)/2
            i -=1
            j -=1

        while i >= 0:
            l = int(a[i])
            ret = str((l+add)%2) + ret
            add = (l+add)/2
            i -= 1
        while j >= 0:
            r = int(b[j])
            ret = str((r+add)%2) + ret
            add = (r+add)/2
            j -= 1

        # don't forget add
        if add ==0:
            return ret
        else:
            return "1"+ret