简单的二进制进位,用两个指针分别指向两个字符串,从后向前遍历:
- 如果有进位,保存进位,然后将剩余部分加入新字符串
- 遍历完某个字符串后,如果存在进位或另一个字符串没有遍历完,继续处理剩余部分
- 遍历完毕后将字符串进行反转即可
代码如下:
// // Created by jt on 2020/9/26. // #include <string> using namespace std; class Solution { public: /** * * @param a string字符串 * @param b string字符串 * @return string字符串 */ string addBinary(string a, string b) { // write code here string c; int p = a.size() - 1, q = b.size() - 1, carry = 0; while (p >= 0 && q >= 0) { int d = a[p] - '0' + b[q] - '0' + carry; if (d > 1) { carry = 1; c.push_back(d - 2 + '0'); } else { carry = 0; c.push_back(d+'0'); } --p; --q; } while (p >= 0) { int d = a[p] - '0' + carry; if (d > 1) { carry = 1; c.push_back(d - 2 + '0'); } else { carry = 0; c.push_back(d+'0'); } --p; } while (q >= 0) { int d = b[q] - '0' + carry; if (d > 1) { carry = 1; c.push_back(d - 2 + '0'); } else { carry = 0; c.push_back(d+'0'); } --q; } if (carry == 1) c.push_back('1'); reverse(c.begin(), c.end()); return c; } };