Description
Given binary strings, return their sum (also a binary string).
Example
A =11
b =1
Return100
Problem solving: binary addition. My idea is, first turn to StringBuilder object (reverse method is useful), because the addition is from the last, so first reversed with the reverse method. Similar to the previous question, the carry variable is used to denote carry, 0 is not carry, and 1 is required to be in a position. The final result is reversed. The details are labeled in the code as follows:
Public classSolution {/** * @paramA:A Number *@paramb:a Number *@return: The result*/ Publicstring Addbinary (String A, string b) {//Write your code hereStringBuilder SA =NewStringBuilder (a); StringBuilder SB=NewStringBuilder (b); StringBuilder Res=NewStringBuilder (); intcarry = 0;//denotes roundingSa.reverse (); Sb.reverse (); inti = 0; for(i = 0; i < sa.length () && i < sb.length (); i++){ intTPA = Sa.charat (i)-' 0 '; intTPB = Sb.charat (i)-' 0 '; if(Carry = = 0) {//No rounding if(TPA = = 1 && TPB = = 1) {Carry= 1; Res.append (' 0 '); }Else{ Chartemp = (Char)((int) ' 0 ' + (tpa+tpb)); Res.append (temp); } }Else{//have carry; if(tpa + TPB = = 1) {Carry= 1;//There's still carry.Res.append (' 0 '); }Else if(tpa + TPB = = 2) {Carry= 1; Res.append (' 1 '); }Else{ //0 + 0Carry = 0; Res.append (' 1 '); } } } //to the rest of the treatment while(I <sa.length ()) { //connect the back of the SA, but consider rounding if(Carry = = 0) {res.append (sa.substring (i)); Break; }Else{ //with rounding if(Sa.charat (i) = = ' 1 ') {res.append (' 0 '); }Else{res.append (' 1 '); Carry= 0; } I++; } } while(I <sb.length ()) { //connect the back of the SA, but consider rounding if(Carry = = 0) {res.append (sb.substring (i)); Break; }Else{ //with rounding if(Sb.charat (i) = = ' 1 ') {res.append (' 0 '); }Else{res.append (' 1 '); Carry= 0; } I++; } } if(Carry = = 1) Res.append (' 1 '); returnres.reverse (). toString (); }}
408. Add Binary "Lintcode java"