首页 > 代码库 > LeetCode Add Binary

LeetCode 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) {
        stack<int> s;
        int na = a.size() - 1;
        int nb = b.size() - 1;

        int c = 0;
        while (na > -1 || nb > -1) {
            int va = 0;
            if (na > -1) {
                va = a[na] - ‘0‘;
                na--;
            }
            int vb = 0;
            if (nb > -1) {
                vb = b[nb] - ‘0‘;
                nb--;
            }

            int tmp = va + vb + c;
            c = tmp / 2;
            s.push(tmp % 2);
        }

        if (c != 0) s.push(c);

        string ans;
        while (!s.empty()) {
            ans.push_back(s.top()+‘0‘);
            s.pop();
        }

        return ans;
    }
};



LeetCode Add Binary