brutal force:
public String addBinary(String a, String b) {
String result="";
int aStrLength=a.length();
int bStrLength=b.length();
String shortStr;
String longStr;
int shortStrLength;
int longStrLength;
int remainder=0;
int carry=0;
if(aStrLength<bStrLength){
shortStr=a;
longStr=b;
shortStrLength=aStrLength;
longStrLength=bStrLength;
}else{
shortStr=b;
longStr=a;
shortStrLength=bStrLength;
longStrLength=aStrLength;
}
for(int i=0;i<shortStrLength;i++){
remainder=((shortStr.charAt(shortStrLength-i-1)-'0')+(longStr.charAt(longStrLength-i-1)-'0')+carry)%2;
result+=(char)(remainder+'0');
carry=((shortStr.charAt(shortStrLength-i-1)-'0')+(longStr.charAt(longStrLength-i-1)-'0')+carry)/2;
}
for(int i=longStrLength-shortStrLength-1;i>-1;i--){
remainder=(longStr.charAt(i)-'0'+carry)%2;
result+=(char)(remainder+'0');
carry=(longStr.charAt(i)-'0'+carry)/2;
}
if(carry==1)
result+=(char)(1+'0');
StringBuffer stringBuffer=new StringBuffer(result);
result=stringBuffer.reverse().toString();
return result;
}
|