# 13 Lines Easy JAVA Solution, Simple and Elegant

• ``````public String addBinary(String a, String b) {
int lena = a.length();
int lenb = b.length();
int i =0, carry = 0;
String res = "";
while(i<lena || i<lenb || carry!=0){
int x = (i<lena) ? Character.getNumericValue(a.charAt(lena - 1 - i)) : 0;
int y = (i<lenb) ? Character.getNumericValue(b.charAt(lenb - 1 - i)) : 0;
res = (x + y + carry)%2 + res;
carry = (x + y + carry)/2;
i++;
}
return res;
}``````

• if you don't want to use getNumericValue:

``````public class Solution {
public String addBinary(String a, String b) {
int carry=0;
String result="";
int i=0;
int alen=a.length();
int blen=b.length();
while(i<alen||i<blen||carry!=0){
int x=(i<alen)?((a.charAt(alen-1-i)=='1')?1:0):0;
int y=(i<blen)?((b.charAt(blen-1-i)=='1')?1:0):0;
result=(x+y+carry)%2+result;
carry=(x+y+carry)/2;
i++;
}
return result;
}
``````

}

• What is carry used for?

• use StringBuilder is much better

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.