67.Add Binary
思路:
- 先翻转,然后相加。(需要多了解一些操作字符串的函数,能方便好多)。
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int carry = 0;
int valA;
int valB;
reverse(begin(a),end(a));
reverse(begin(b),end(b));
int n = max(a.length(),b.length());
for(int i = 0; i < n; i ++){
valA = i < a.length() ? a[i] - '0' : 0;
valB = i < b.length() ? b[i] - '0' : 0;
res.insert(begin(res),(carry + valA + valB)%2+'0');
carry = (carry + valA + valB) / 2;
}
if(carry) res.insert(begin(res),'1');
return res;
}
};