Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
This topic just pay attention to all kinds of situations and you'll make it. More than half, it is particularly important to note that possible changes to the carry value, and the last digit to be 1 o'clock,
We're going to put this 1 in. Also note that the low of the string is our high value.
classSolution { Public: stringAddbinary (stringAstringb) {reverse (Begin (a), End (a)); Reverse (begin (b), end (b)); stringresult; Charnum ='0'; inti =0; for(; i < a.size () && i < b.size (); + +i) {if(A[i] = ='0'&&b[i] = ='0'&&num = ='0') {Result.insert (begin),'0'); } if(A[i] = ='1'&&b[i] = ='1'&&num = ='1') {Result.insert (begin),'1'); } if((a[i] = ='0'&&b[i] = ='1'&&num = ='1') || (A[i] = ='1'&&b[i] = ='0'&&num = ='1') ||(A[i]=='1'&&b[i] = ='1'&&num = ='0') {Result.insert (begin (Result),'0'); Num='1'; } if(A[i] = ='1'&&b[i] = ='0'&&num = ='0'|| A[i] = ='0'&&b[i] = ='1'&&num = ='0'||A[i]=='0'&&b[i] = ='0'&&num = ='1') {Result.insert (begin),'1'); Num='0'; } } if(i = =a.size ()) { for(; i < b.size (); + +i) {if(B[i] = ='0'&&num = ='0') Result.insert (begin (Result),'0'); if(B[i] = ='0'&&num = ='1'|| B[i] = ='1'&&num = ='0') {Result.insert (begin),'1'); Num='0'; } if(B[i] = ='1'&&num = ='1') Result.insert (begin (Result),'0'); } } Else { for(; i < a.size (); + +i) {if(A[i] = ='0'&&num = ='0') Result.insert (begin (Result),'0'); if(A[i] = ='1'&&num = ='1') Result.insert (begin (Result),'0'); if(A[i] = ='0'&&num = ='1'|| A[i] = ='1'&&num = ='0') {Result.insert (begin),'1'); Num='0'; } } } if(num = ='1') Result.insert (Begin (Result),'1'); returnresult; }};
Leetcode 67. ADD Binary