题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
提示:
此题我的第一反应是把输入的两个字符串转化为数字,相加以后再把结果转化为二进制输出,但是测试用例中会有很大的输入,此时即使是long long型也会造成溢出,所以只能用最传统的由低位到高位逐位相加的方法去做。
代码:
class Solution { public: string addBinary(string a, string b) { int len_a = a.size() - 1, len_b = b.size() - 1; int dif = abs(len_a - len_b); string prev = ""; for (int i = 0; i < dif; ++i) prev += '0'; if (len_a < len_b) a = prev + a; else b = prev + b; int len = a.size(), step = 0; vector<int> v; for (int i = len - 1; i > -1; --i) { step += a[i] + b[i] - ('0' << 1); v.push_back(step % 2); step = step >> 1; } if (step) v.push_back(step % 2); string res; for (int i = v.size() - 1; i > -1; --i) { res += ('0' + v[i]); } return res; } };