LeetCode 67. Add Binary

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

For example,
a = "11"
b = "1"
Return "100".


// Only need to pay attention that adding is from the end of string. 

This problem is similar to the add one problem. http://blog.csdn.net/github_34333284/article/details/51103310

#include <string>
#include <iostream>
using namespace std;

// a = "11", b = "1" --> "100"

string addBinary(string a, string b) {
    if(a.size() == 0) return b;
    if(b.size() == 0) return a;
    int aSize = a.size() - 1;
    int bSize = b.size() - 1;
    string res = "";
    int overflow = 0;
    while(aSize >= 0 && bSize >= 0) {
        int tmp = a[aSize] - '0' + b[bSize] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
        aSize--;
        bSize--;
    }
    while(aSize >= 0) {
        int tmp = a[aSize--] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
    }
    while(bSize >= 0) {
        int tmp = b[bSize--] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
    }
    if(overflow) res = "1" + res;
    return res;
}

int main(void) {
    string a = "11";
    string b = "1";
    string res = addBinary(a, b);
    cout << res << endl;
}


你可能感兴趣的:(LeetCode 67. Add Binary)