My 4ms C++ solution


  • 0
    J
    string addBinary(string a, string b) {
        string ret;
        int flag = 0;
        int tmp;
        int i, j;
        for(i = a.size() - 1, j = b.size() - 1; i >= 0 && j >= 0; --i, --j){
            tmp = a[i] - '0' + b[j] - '0' + flag;
            flag = tmp / 2;
            if(tmp > 1){
                ret += to_string(tmp%2);
            }
            else{
                ret += to_string(tmp);
            }
        }
        if(flag){
            // only one while-loop will run
            while(i >= 0){
                tmp = a[i--] -'0' + flag;
                flag = tmp / 2;
                if(tmp > 1){
                    ret += to_string(tmp%2);
                }
                else{
                    ret += to_string(tmp);
                }
            }
            while(j >= 0){
                tmp = b[j--] - '0' + flag;
                flag = tmp / 2;
                if(tmp > 1){
                    ret += to_string(tmp%2);
                }
                else{
                    ret += to_string(tmp);
                }
            }
            if (flag) {
                ret += "1";
            }
        }
        else{
            // only one wihle-loop will run
            while(i >= 0){
                ret += to_string(a[i--] - '0');
            }
            while(j >= 0){
                ret += to_string(b[j--] - '0');
            }
        }
        return reverse(ret);
    }
    
    string reverse(string str){
        string ret;
        for(int i = str.size() - 1; i >= 0; --i){
            ret += str[i];
        }
        return ret;
    }

Log in to reply
 

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