67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

class Solution {
public:
    string addBinary(string a, string b) {
        int c = 0, quo = 0, i, j;
        string ans;
        for(i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; --i, --j){
            if(i >= 0 && j >= 0){
                quo = (a[i] - '0' + b[j] - '0' + c) % 2;
                c = (a[i] - '0' + b[j] - '0' + c) / 2;
            } else if(i >= 0){
                quo = (a[i] - '0' + c) % 2;
                c = (a[i] - '0' + c) / 2;
            } else if(j >= 0){
                quo = (b[j] - '0' + c) % 2;
                c = (b[j] - '0' + c) / 2;
            }
            ans.insert(ans.begin(), (quo + '0'));
        }

        if(c != 0)
            ans.insert(ans.begin(), (c + '0'));
        return ans;
    }
};

二刷

class Solution {
public:
    string addBinary(string a, string b) {
        string res;
        int i, j, carry = 0;
        for(i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j){
            res.push_back((a[i] - '0' + b[j] - '0' + carry) % 2 + '0');
            carry = (a[i] - '0' + b[j] - '0' + carry) / 2;
        }
        while(i >= 0){
            res.push_back((a[i] - '0' + carry) % 2 + '0');
            carry = (a[i] - '0' + carry) / 2;
            --i;
        }
        while(j >= 0){
            res.push_back((b[j] - '0' + carry) % 2 + '0');
            carry = (b[j] - '0' + carry) /  2;
            --j;
        }
        if(carry) res.push_back('1');

        string rev;
        int len = res.length();
        for(i = len - 1; i >= 0; --i){
            rev.push_back(res[i]);
        }
        return rev;
    }
};
阅读更多
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

67. Add Binary

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭