67. Add Binary(二进制求和)
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
class Solution { public: string addBinary(string a, string b) { int carry = 0; int a_s = a.size()-1, b_s = b.size()-1; string res = ""; while(a_s>=0||b_s>=0) { int a_int = a_s >=0 ?a[a_s]-'0':0; int b_int = b_s >=0 ?b[b_s]-'0':0; int cur = a_int + b_int + carry; carry = cur>=2?1:0; string cur_res = cur%2==1?"1":"0"; res.append(cur_res); a_s--;b_s--; } if (carry) res.append("1"); reverse(res.begin(), res.end()); return res; } };