Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
Problem Solving Ideas:
The Java implementation is as follows:
static public string Addbinary (string A, string b) {if (A.length () < B.length ()) {String temp = A;a = B;b = temp;} Boolean carry = false; StringBuilder sb = new StringBuilder (a); for (int i = 0; i < b.length (); i++) {if (B.charat (B.length ()-1-i) = = ' 0 ') {if (Sb.charat (A.length ()-1-i) = = ' 0 ' && carry) {Sb.replace (A.length ()-1-i, A.length ()-I, "1"); carry = f Alse;} else if (Sb.charat (A.length ()-1-i) = = ' 1 ' && carry) Sb.replace (A.length ()-1-i, A.length ()-I, "0");} else {if (Sb.charat (A.length ()-1-i) = = ' 0 ' &&!carry) sb.replace (A.length ()-1-i, A.length ()-I, "1"); else if (Sb.charat (A.length ()-1-i) = = ' 1 ' &&!carry) {sb.replace (A.length ()-1-i, A.length ()-I, "0"); carry = t Rue;}}} if (!carry) return sb.tostring (); for (int i = A.length ()-B.length ()-1; I >= 0; i--) if (Sb.charat (i) = = ' 0 ') {SB.REPL Ace (I, i + 1, "1"); return sb.tostring ();} Elsesb.replace (i, i + 1, "0"); Sb.insert (0, ' 1 '); return sb.tostring ();}
Java for Leetcode 067 Add Binary