https://leetcode-cn.com/problems/add-binary/
class Solution {
public String addBinary(String a, String b) {
a=new StringBuilder(a).reverse().toString();
b=new StringBuilder(b).reverse().toString();
boolean flag = false;
String ans= longer(a,b);
a=shorter(a,b);
char[] ansarr=ans.toCharArray();
char[] aarr=a.toCharArray();
for (int i=0;i<aarr.length;i++) {
ansarr[i]= (char) (ansarr[i]+aarr[i]-'0');
}
for (int i=0;i<ansarr.length;i++){
if (ansarr[i]>='2') {
if (i==ansarr.length-1) {
flag=true;
ansarr[i]= (char) (ansarr[i]%'2'+'0');
} else {
ansarr[i+1]= (char) (ansarr[i+1]+ansarr[i]/'2');
ansarr[i]= (char) (ansarr[i]%'2'+'0');
}
}
}
ans=flag?String.valueOf(ansarr)+"1":String.valueOf(ansarr);
return new StringBuilder(ans).reverse().toString();
}
public static String longer(String x,String y) {
if(x.length()>=y.length()) {
return x;
}else {
return y;
}
}
public static String shorter(String x,String y) {
if(x.length()<y.length()) {
return x;
}else {
return y;
}
}
}