# My c++ solution (6ms, easy to understand)

• ``````class Solution {
public:
string addBinary(string a, string b) {
int len_a = a.length() - 1;
int len_b = b.length() - 1;
int len_res = len_a > len_b ? len_a : len_b;
string res(len_res + 1, 0x32);
int flag = 0, tmp;
while (len_a >= 0 || len_b >= 0) {
if (len_a >=0 && len_b < 0)
tmp = a[len_a--] - 0x30 + flag;
else if (len_b >= 0 && len_a < 0)
tmp = b[len_b--] - 0x30 + flag;
else
tmp = a[len_a--] - 0x30 + b[len_b--] - 0x30 + flag;

res[len_res--] = tmp % 2 + 0x30;
flag = tmp / 2;
}
if (flag == 1)
res = "1" + res;
return res;
}
};``````

• This post is deleted!

• Hi, I'm confused with string res(len_res + 1, 0x32); why should we set length len_res+1 instead of len_res, and why should we initialize every char in res to be 0x32?

• Actually, the variables len do not mean length, they mean the array indices. Like:

int len_a = a.length() - 1; Here, a.length() means the length of string a.

I want to define a new string with a specific length, only this constructor can be used, "sting(sizt_t n, char c)". So I must give two parameters. 0x32 means nothing, any number is ok, but in case of the influence of 0/1, I give a 2.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.