public String addBinary(String a,String b){
  int m=a.length();
  int n=b.length();
  int carry=0;
  StringBuilder res=new StringBuilder();
  int i=0;
  while (i < m || i < n) {
    int p=i < m ? a.charAt(m - 1 - i) - '0' : 0;
    int q=i < n ? b.charAt(n - 1 - i) - '0' : 0;
    int temp=p + q + carry;
    carry=temp / 2;
    res.insert(0,temp % 2);
    i++;
  }
  return carry == 0 ? res.toString() : "1" + res.toString();
}

public String addBinary ( String a , String b ) { int m = a . length ( ) ; int n = b . length ( ) ; int carry = 0 ; StringBuilder res = new StringBuilder ( ) ; int i = 0 ; while ( i < m || i < n ) { int p = i < m ? a . charAt ( m - 1 - i ) - '0' : 0 ; int q = i < n ? b . charAt ( n - 1 - i ) - '0' : 0 ; int temp = p + q + carry ; carry = temp / 2 ; res . insert ( 0 , temp % 2 ) ; i ++ ; } return carry == 0 ? res . toString ( ) : "1" + res . toString ( ) ; }
math , string . from right to left , do it digit - by - digit . get current digits of ab and b , add them up . also use an integer to store carry from the previous addition . store the sum to result and update carry for each round . stop when longest string is reached . remember to check carry before return , if carry is 1 , it should still be inserted to the result .
