Question 1ADD Binary
Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
Firslty I Wirte A very direct and kind of brute Forch method. Just consider each case of the sum 1, 0, 2, 3 for Anum + Bnum + carry by switch case.
1 Public classSolution {2 3String result = "";4 intCarry = 0;5 6 Publicstring Addbinary (String A, string b) {7 if(a.length () = = 0 )8 returnb;9 Else if(b.length () = = 0)Ten returnA; One A - intAlen = A.length ()-1; - intBlen = B.length ()-1; the - - while(Alen >= 0 && Blen >=0){ - intAnum = A.charat (alen)-' 0 '; + intBnum = B.charat (blen)-' 0 '; -Calculator (Anum + bnum +carry); +Alen--; ABlen--; at } - - while(Alen >= 0){ - intAnum = A.charat (alen)-' 0 '; -Calculator (Anum +carry); -Alen--; in } - to while(Blen >= 0){ + intBnum = B.charat (blen)-' 0 '; -Calculator (Bnum +carry); theBlen--; * } $ Panax Notoginseng if(Carry = = 1) -result = "1" +result; the + returnresult; A } the + Public voidCalculatorintsum) { - Switch(sum) { $ Case0: $result = "0" +result; - Break; - Case1: theresult = "1" +result; -Carry = 0;Wuyi Break; the Case2: -result = "0" +result; WuCarry = 1; - Break; About Case3: $result = "1" +result; -Carry = 1; - Break; - } A } +}
The other-the-does not-use-switch case but use%2 OR/2-defind carry and Sum, which is much clear and shorter.
1 Publicstring Addbinary (String A, string b) {2 if(a.length () = = 0 )3 returnb;4 Else if(b.length () = = 0)5 returnA;6 7String result = "";8 intCarry = 0;9 Ten intLen =Math.max (A.length (), b.length ()); One A for(inti = 0; i < Len; i + +){ - intAnum = 0; - intBnum = 0; the if(I <a.length ()) -Anum = A.charat (A.length ()-1-i)-' 0 '; - if(I <b.length ()) -Bnum = B.charat (B.length ()-1-i)-' 0 '; + - intsum = anum + Bnum +carry; +result = sum%2 +result; Acarry = SUM/2; at } - - if(Carry = = 1) -result = "1" +result; - - returnresult; in -}
Leetcode--DAY13