67. Add Binary

Problem:

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

思路

Solution (C++):

string addBinary(string a, string b) {
    int m = a.size(), n = b.size(), carry = 0, i = 0, digit = 0;
    vector<int> v;
    while (i < m && i < n) {
        digit = int(a[m-1-i]) -48 + int(b[n-1-i]) -48 + carry;
        carry = digit / 2;
        digit %= 2;
        v.push_back(digit);
        ++i;
    }
    if (i < m) {
        while (i < m) {
            digit = int(a[m-1-i]) -48 + carry;
            carry = digit / 2;
            digit %= 2;
            v.push_back(digit);
            ++i;
        }
    }
    if (i < n) {
        while (i < n) {
            digit = int(b[n-1-i]) -48 + carry;
            carry = digit / 2;
            digit %= 2;
            v.push_back(digit);
            ++i;
        }
    }
    
    if (carry == 1) v.push_back(carry);
    string res = "";
    for (int j = 0; j < v.size(); ++j) {
        res += to_string(v[v.size()-j-1]);
    }
    return res;
}

性能

Runtime: 4 ms  Memory Usage: 6.8 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-03-28 11:10  littledy  阅读(66)  评论(0编辑  收藏  举报