描述 Given two binary strings, return their sum (also a binary string).
For example, a = “11” b = “1” Return “100”.
分析 翻转a和b,逐位相加求值,结果存入string中。 注意最高位的情况。
代码
class Solution {public: string addBinary(string a, string b) { string result; size_t n = a.size() > b.size() ? a.size() : b.size(); int carry = 0; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); for (size_t i = 0; i < n; ++i) { const int ai = i < a.size() ? a[i] - '0' : 0; const int bi = i < b.size() ? b[i] - '0' : 0; const int val = (ai + bi + carry) % 2; carry = (ai + bi + carry) / 2; result.insert(result.begin(), val + '0'); } if (carry == 1) result.insert(result.begin(), '1'); return result; }};新闻热点
疑难解答