Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
1 public class Solution { 2 public String addBinary(String a, String b) { 3 if (a == null || a == "") 4 return b; 5 if (b == null || b == "") 6 return a; 7 int carry = 0; 8 String ret = ""; 9 int l1 = a.length()-1; 10 int l2 = b.length()-1; 11 while (l1 >= 0 || l2 >= 0 || carry == 1) { 12 if (l1 >= 0) { 13 carry += Integer.parseInt(a.charAt(l1)+""); 14 l1--; 15 } 16 if (l2 >= 0) { 17 carry += Integer.parseInt(b.charAt(l2)+""); 18 l2--; 19 } 20 ret = String.valueOf(carry%2) + ret; 21 carry /= 2; 22 } 23 return ret; 24 } 25 }