LeetCode 67,二进制求和

题目描述:给定两个二进制字符串,返回他们的和(用二进制表示)。输入为非空字符串且只包含数字 1 和 0

    string addBinary(string a, string b) {
        stack<char> s_a,s_b;
        for(int i = 0;i<a.size();++i){
            s_a.push(a[i]);
        }
        for(int i = 0;i<b.size();++i){
            s_b.push(b[i]);
        }
        int jinwei = 0;
        stack<char> ans;
        while(!s_a.empty()&&!s_b.empty()){
            int re_wei = s_a.top()-'0'+s_b.top()-'0'+jinwei;
            if(re_wei<=1) {
                char s = re_wei+'0';
                ans.push(s);
                jinwei = 0;
            }
            else if(re_wei<3){
                ans.push('0');
                jinwei = 1;
            }
            else{
                ans.push('1');
                jinwei = 1;                
            }
            s_a.pop();
            s_b.pop();
        }
        if(s_a.empty()&&!s_b.empty()){
            while(!s_b.empty()){
                int re_wei = s_b.top()-'0'+jinwei;
                if(re_wei<=1) {
                    char s = re_wei+'0';
                    ans.push(s);
                    jinwei = 0;
                }
                else{
                    ans.push('0');
                    jinwei = 1;
                }
                s_b.pop(); 
            }
        }
        else if(!s_a.empty()&&s_b.empty()){
                while(!s_a.empty()){
                int re_wei = s_a.top()-'0'+jinwei;
                if(re_wei<=1) {
                    char s = re_wei+'0';
                    ans.push(s);
                    jinwei = 0;
                }
                else{
                    ans.push('0');
                    jinwei = 1;
                }
                s_a.pop(); 
            }
        }
        if(jinwei==1) ans.push('1');
        string add;
        while(!ans.empty()){
            add+=ans.top();
            ans.pop();
        }
        return add;
    }

各种if判断,用了stack空间换时间。题解中对短字符进行补长操作

执行用时 :4 ms, 在所有 cpp 提交中击败了90.23%的用户 

内存消耗 :9.3 MB, 在所有 cpp 提交中击败了8.74%的用户

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值