首页 > 代码库 > Add Binary

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"

Return "100".

public class Solution {
    public String addBinary(String a, String b) {
        int alen=a.length();
    	int blen=b.length();
    	int len=alen>blen?(alen+1):(blen+1);
    	StringBuffer sba=new StringBuffer(a).reverse();
    	StringBuffer sbb=new StringBuffer(b).reverse();
    	while(sba.length()<len) sba.append("0");
    	while(sbb.length()<len) sbb.append("0");
    	
    	StringBuffer sb=new StringBuffer("");
    	int tmp = 0;
    	for(int i=0;i<len;i++){
    	
    		int ia=(int) (sba.charAt(i)-'0');
    		int ib=(int) (sbb.charAt(i)-'0');
    		int ic=ia+ib+tmp;
    		tmp=0;
    		if(ic==3){
    			sb.append("1");
    			tmp=1;
    		}
    		else if( ic==2){
    			sb.append("0");
    			tmp=1;
    		}
    		else{
    			new String();
    			sb.append(String.valueOf(ic));
    			tmp=0;
    		}
    	}
    	// if last is 0 ; then delete
    	if(sb.charAt(sb.length()-1)=='0')
    		sb.deleteCharAt(sb.length()-1);
        return sb.reverse().toString();
    }
}