Posted onEdited onInLeetCodeDisqus: Symbols count in article: 854Reading time ≈1 mins.
O(max(m, n)) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: stringaddBinary(string a, string b){ string res; for (int c = 0, i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0 || c > 0; --i, --j) { int x = i < 0 ? 0 : (a[i] - '0'); int y = j < 0 ? 0 : (b[j] - '0'); int s = x + y + c; res += '0' + (s & 1); c = s >> 1; } returnstring(rbegin(res), rend(res)); } };
classSolution { public: stringaddBinary(string a, string b){ if (a.empty()) return b; if (b.empty()) return a; int c = 0; string res; while (!a.empty() || !b.empty() || c > 0) { int x = a.empty() ? 0 : (a.back() - '0'); int y = b.empty() ? 0 : (b.back() - '0'); if (!a.empty()) { a.pop_back(); } if (!b.empty()) { b.pop_back(); } int s = x + y + c; res += '0' + (s & 1); c = (s >> 1); } returnstring(rbegin(res), rend(res)); } };