Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解法:从后往前对两个string相加即可。注意将char转换为int,注意进位,注意结果顺序。
class Solution { public: string addBinary(string a, string b) { int as = a.size(), bs = b.size(); if (bs > as) return addBinary(b, a); int i = as - 1, j = bs - 1, carry = 0; string res = ""; while (i >= 0) { int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0); res += (char)(curr % 2 + '0'); carry = curr / 2; i--; j--; } res = carry == 1 ? res + '1' : res; reverse(res.begin(), res.end()); return res; } };
或者直接使用string的insert成员函数:
class Solution { public: string addBinary(string a, string b) { int as = a.size(), bs = b.size(); if (bs > as) return addBinary(b, a); int i = as - 1, j = bs - 1, carry = 0; string res = ""; while (i >= 0) { int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0); res.insert(0, 1, (char)(curr % 2 + '0')); carry = curr / 2; i--; j--; } res = carry == 1 ? res.insert(0, 1, '1') : res; return res; } };