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; } };
原文:http://blog.csdn.net/u011345136/article/details/44784675