My 6ms C++ code


  • -1
    L

    string addBinary(string a, string b) {
    int la=a.size(), lb=b.size();
    if (la==0 || lb==0) return la?a:b;

        string result(max(la,lb)+1,'0');
        int carry = 0;
        int i=0;
        char ca,cb;
        while(i<result.size()){
            if (i<la) ca=a[la-1-i];
            else    ca='0';
            if (i<lb)  cb=b[lb-1-i];
            else    cb='0';
    
            int r = (ca-'0')+(cb-'0')+carry;
            result[i] = r%2+'0';
            carry = r/2;
            i++;
        }
        if (result.back()=='0') result.resize(result.size()-1);
        reverse(result.begin(),result.end());
        return result;
    }

  • 0
    Z
    public static String addBinary(String a, String b) {
    	int maxLength=Math.max(a.length(), b.length());
    	StringBuilder result=new StringBuilder();
    	int carry=0;
    	while(a.length()!=b.length()){
    		if(a.length()>b.length()){
    			b='0'+b;
    		}else if(a.length()<b.length()){
    			a='0'+a;
    		}
    		
    	}
    	for(int i=maxLength-1;i>=0;i--){
    		int temp=a.charAt(i)+b.charAt(i)-'0'-'0'+carry;
    		carry=temp/2;
    		temp=temp%2;
    		char tc=(char) (temp+'0');
    		result.append(tc);
    	}
    	if(carry>0) result.append(carry);
    	return result.reverse().toString();
    } 

Log in to reply
 

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