File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def addBinary (self , a : str , b : str ) -> str :
3
+ l_max = max (len (a ), len (b ))
4
+ l = l_max - min (len (a ), len (b ))
5
+ if len (a ) < len (b ):
6
+ a = '0' * l + a
7
+ if len (b ) < len (a ):
8
+ b = '0' * l + b
9
+
10
+ carry = 0
11
+ answer = ['0' for _ in range (l_max )]
12
+
13
+ for idx in range (- 1 , - l_max - 1 , - 1 ):
14
+ v = int (a [idx ]) + int (b [idx ]) + carry
15
+ if v == 3 :
16
+ carry = 1
17
+ answer [idx ] = str (1 )[0 ]
18
+ elif v == 2 :
19
+ carry = 1
20
+ answer [idx ] = str (0 )[0 ]
21
+ elif v == 1 :
22
+ carry = 0
23
+ answer [idx ] = str (1 )[0 ]
24
+ elif v == 0 :
25
+ carry = 0
26
+ answer [idx ] = str (0 )[0 ]
27
+
28
+ answer = '' .join (answer )
29
+
30
+ if carry == 1 :
31
+ answer = '1' + answer
32
+
33
+ return answer
Original file line number Diff line number Diff line change
1
+ from unittest import TestCase
2
+ from main import Solution
3
+
4
+ class TestSolution (TestCase ):
5
+ def test_add_binary (self ):
6
+ sln = Solution ()
7
+ self .assertEqual (sln .addBinary ('11' , '1' ), '100' )
8
+
9
+ def test_add_binary2 (self ):
10
+ sln = Solution ()
11
+ self .assertEqual (sln .addBinary ('1010' , '1011' ), '10101' )
You can’t perform that action at this time.
0 commit comments