We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ce3db28 commit 3ea2d3cCopy full SHA for 3ea2d3c
JianZhiOffer/2.cpp
@@ -0,0 +1,38 @@
1
+#include <iostream>
2
+#include <algorithm>
3
+#include <string>
4
+
5
+using namespace std;
6
7
+class Solution {
8
+public:
9
+ string addBinary(string a, string b) {
10
+ int la = a.size() - 1;
11
+ int lb = b.size() - 1;
12
+ int carry = 0;
13
+ string results;
14
+ while(la >= 0 || lb >= 0)
15
+ {
16
+ int aa = la >= 0 ? a[la] - '0' : 0;
17
+ int bb = lb >= 0 ? b[lb] - '0' : 0;
18
+ int sum = aa + bb + carry;
19
+ carry = sum >= 2 ? 1: 0;
20
+ sum = sum >= 2 ? sum - 2: sum;
21
22
+ results.push_back('0' + sum);
23
+ la -= 1;
24
+ lb -= 1;
25
+ }
26
+ if (carry == 1)
27
+ results.push_back('1');
28
+ reverse(results.begin(), results.end());
29
+ return results;
30
31
+};
32
33
+int main(void)
34
+{
35
+ Solution sol = Solution();
36
+ string results = sol.addBinary("101111", "10");
37
+ cout << results << endl;
38
+}
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments