【leetcode】67. Add Binary

@requires_authorization
@author johnsondu
@create_time 2015.7.15 11:00
@url [add binary](https://leetcode.com/problems/add-binary/)
/*******************
 *  模拟大数相加
 *  时间复杂度: O(n)
 *  空间复杂度: O(n)
 ******************/
class Solution {
public:
    string addBinary(string a, string b) {
        int lena = a.size();
        int lenb = b.size();
        string ans = "";
        string tmpa = "";
        string tmpb = "";
        for(int i = lena-1; i >= 0; i --) tmpa += a[i];
        for(int i = lenb-1; i >= 0; i --) tmpb += b[i];
        int mins = min(lena, lenb);
        int carry = 0;
        for(int i = 0; i < mins; i ++){
            int res = (tmpa[i] - '0') + (tmpb[i] - '0') + carry; 
            carry = res > 1 ? 1 : 0;
            res = res % 2;
            ans += (res + '0');
        }
        for(int i = mins; i < lena; i ++){
            int res = (tmpa[i] - '0') + carry;
            carry = res > 1 ? 1 : 0;
            res = res % 2;
            ans += (res + '0');
        }
        for(int i = mins; i < lenb; i ++){
            int res = (tmpb[i] - '0') + carry;
            carry = res > 1 ? 1 : 0;
            res = res % 2;
            ans += (res + '0');
        }
        if(carry){
            ans += (carry + '0');
        }
        int len_ans = ans.size();
        for(int i = 0; i < len_ans / 2; i ++){
            char tmp = ans[i];
            ans[i] = ans[len_ans-i-1];
            ans[len_ans-i-1] = tmp;
        }
        return ans;
    }
};
// Simplified Version
class Solution {
public:
    string addBinary(string a, string b) {
        int lena = a.size() - 1;
        int lenb = b.size() - 1;
        string ans = "";
        int carry = 0;
        while(lena >= 0 || lenb >= 0 || carry > 0){
            int res = carry;
            if(lena >= 0) res += (a[lena] - '0');
            if(lenb >= 0) res += (b[lenb] - '0');

            carry = res / 2;
            ans = string(1, (res & 1) + '0') + ans;
            lena --;
            lenb --;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值