【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;
    }
};
posted @ 2017-06-22 08:46  yfceshi  阅读(174)  评论(0编辑  收藏  举报