Problem
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
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
Code
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int a_z = a.size();
int b_z = b.size();
if (a_z<b_z) {
for (int i = 0; i<b_z - a_z; i++)
a = "0" + a;
}
else {
for (int i = 0; i<a_z - b_z; i++) {
b = "0" + b;
}
}
bool flag = false;
for (int i = a.size() - 1; i >= 0; i--) {
if (a[i] == '1' && b[i] == '1') {
if (flag)
res = "1" + res;
else
res = "0" + res;
flag = true;
}
else if (a[i] == '0' && b[i] == '0') {
if (flag)
res = "1" + res;
else
res = "0" + res;
flag = false;
}
else {
if (flag)
res = "0" + res;
else
res = "1" + res;
}
}
if (flag)
res = "1" + res;
return res;
}
};
网友评论