二进制求和
题目描述
给你两个二进制字符串 a
和 b
,以二进制字符串的形式返回它们的和。
示例 1:
1 2
| 输入:a = "11", b = "1" 输出:"100"
|
示例 2:
1 2
| 输入:a = "1010", b = "1011" 输出:"10101"
|
提示:
1 <= a.length, b.length <= 104
a
和 b
仅由字符 '0'
或 '1'
组成
- **字符串如果不是 **
"0"
,就不含前导零
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> #include <string> using namespace std;
class Solution { public: string addBinary(string a, string b) { if (a.length() < b.length()) { swap(a, b); } while (b.length() < a.length()) { b = "0" + b; } string result = ""; int carry = 0; for (int i = 0; i < a.length(); ++i) { int sum = (a[a.length() - 1 - i] - '0') + (b[b.length() - 1 - i] - '0') + carry; carry = sum / 2; result = to_string(sum % 2) + result; } if (carry > 0) { result = "1" + result; } return result; } };
int main() { Solution s; cout << s.addBinary("11", "1") << endl; return 0; }
|