Total Accepted: 78879 Total
Submissions: 291470 Difficulty: Easy
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
Hide Similar Problems
題意:
計算字符串的加法 返回結果字符串。
思路比較簡單,注意字符串拼接以及進位的判斷。
代碼(已AC 2016-03-24)~
string addBinary(string a, string b) {
if (a.empty() || b.empty())
{
return (a.empty()) ? b : a;
}
int inc = 0, posA = a.length() - 1, posB = b.length() - 1, sum = 0;
string res("");
while (posA >= 0 && posB >= 0)
{
sum = (a[posA] - '0') + (b[posB] - '0') + inc;
inc = sum / 2;
res = (char)(sum % 2 + '0') + res;
posA--, posB--;
}
while (posA > -1)
{
sum = (a[posA] - '0') + inc;
inc = sum / 2;
res = (char)(sum % 2 + '0') + res;
posA--;
}
while (posB > -1)
{
sum = (a[posB] - '0') + inc;
inc = sum / 2;
res = (char)(sum % 2 + '0') + res;
posB--;
}
if (inc)
res = (char)(inc + '0') + res;
return res;
}