Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100" .
Public classSolution { Publicstring Addbinary (String A, string b) {//time complexity O (n). Space complexity O (1)//Note: 1. Cautious, pay attention to the way the loop is written, as shown in the non-commented code, and can continue to add even after a traversal//2. Note The handling of the last rounding//3. Note how to add characters to the StringBuilder headStringBuilder seq=NewStringBuilder (); intCarry=0; intI=a.length ()-1; intJ=b.length ()-1; /*For (; j>=0&&i>=0;i--, j--) {int A1=a.charat (i)-' 0 '; int B1=b.charat (j)-' 0 '; int Temp=a1+b1+carry; Seq.insert (0,temp%2); CARRY=TEMP/2; } while (i>=0) {int Temp=a.charat (i)-' 0 ' +carry; Seq.insert (0,temp%2); CARRY=TEMP/2; i--; } while (j>=0) {int Temp=b.charat (j)-' 0 ' +carry; Seq.insert (0,temp%2); CARRY=TEMP/2; j--; }*/ for(; j>=0| | I>=0;i--, j--){ intA1=i>=0?a.charat (i)-' 0 ': 0; intB1=j>=0?b.charat (j)-' 0 ': 0; inttemp=a1+b1+carry; Seq.insert (0,temp%2); Carry=temp/2; } if(carry>0) Seq.insert (0, carry); returnseq.tostring (); }}
[Leedcode 67] ADD Binary