File tree Expand file tree Collapse file tree
LeetCode.Algorithms.Tests/A
LeetCode.Algorithms/LeetCode.Algorithms/A Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ namespace LeetCode . Algorithms . Tests ;
2+
3+ public class Add_Binary
4+ {
5+ [ Theory ]
6+ [ InlineData ( "11" , "1" , "100" ) ]
7+ [ InlineData ( "1010" , "1011" , "10101" ) ]
8+ [ InlineData ( "1" , "111" , "1000" ) ]
9+ [ InlineData ( "101111" , "10" , "110001" ) ]
10+ public void AddBinary ( string a , string b , string expected )
11+ {
12+ new Algorithms . Add_Binary ( ) . AddBinary ( a , b ) . Should ( ) . Be ( expected ) ;
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ using System . Text ;
2+
3+ namespace LeetCode . Algorithms ;
4+
5+ public class Add_Binary
6+ {
7+ public string AddBinary ( string a , string b )
8+ {
9+ var builder = new StringBuilder ( ) ;
10+ var max = ( a . Length > b . Length ? a : b ) . Reverse ( ) . ToList ( ) ;
11+ var min = ( b . Length >= a . Length ? a : b ) . Reverse ( ) . ToList ( ) ;
12+ var hand = 0 ;
13+ for ( var i = 0 ; i < max . Count ; i ++ )
14+ {
15+ if ( i >= min . Count )
16+ {
17+ if ( max [ i ] == '1' && hand == 1 )
18+ {
19+ builder . Append ( '0' ) ;
20+ }
21+ else if ( hand == 1 )
22+ {
23+ builder . Append ( '1' ) ;
24+ hand = 0 ;
25+ }
26+ else
27+ {
28+ builder . Append ( max [ i ] ) ;
29+ }
30+
31+ continue ;
32+ }
33+ if ( max [ i ] == '1' && min [ i ] == '1' )
34+ {
35+ if ( hand == 1 )
36+ {
37+ builder . Append ( '1' ) ;
38+ }
39+ else
40+ builder . Append ( '0' ) ;
41+ hand = 1 ;
42+
43+ }
44+ else if ( max [ i ] == '1' || min [ i ] == '1' )
45+ {
46+ if ( hand == 1 )
47+ {
48+ builder . Append ( '0' ) ;
49+ }
50+ else
51+ {
52+ builder . Append ( '1' ) ;
53+ }
54+ }
55+ else
56+ {
57+ if ( hand == 1 )
58+ {
59+ builder . Append ( '1' ) ;
60+ hand = 0 ;
61+ }
62+ else
63+ {
64+ builder . Append ( '0' ) ;
65+ }
66+ }
67+ }
68+
69+ if ( hand == 1 )
70+ builder . Append ( '1' ) ;
71+
72+ return string . Join ( "" , builder . ToString ( ) . Reverse ( ) ) ;
73+ }
74+ }
You can’t perform that action at this time.
0 commit comments