码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】67. Add Binary

时间:2015-07-15 13:20:57      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:leetcode   addbinary   algorithm   

@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;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】67. Add Binary

标签:leetcode   addbinary   algorithm   

原文地址:http://blog.csdn.net/zone_programming/article/details/46890397

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!