Leetcode 67. Add Binary

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Add Binary

2. Solution

  • Version 1
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
36
37
38
39
40
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int min = 0;
int max = 0;
int carry = 0;
string s;
string result;
if(a.length() > b.length()) {
max = a.length();
min = b.length();
s = a;
}
else {
max = b.length();
min = a.length();
s = b;
}
for(int i = 0; i < min; i++) {
int x = a[i] - 48;
int y = b[i] - 48;
int sum = x + y + carry;
result += to_string(sum % 2);
carry = sum>1?1:0;
}
for(int i = min; i < max; i++) {
int x = s[i] - 48;
int sum = x + carry;
result += to_string(sum % 2);
carry = sum>1?1:0;
}
if(carry) {
result += to_string(carry);
}
reverse(result.begin(), result.end());
return result;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string addBinary(string a, string b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
string result;
while(i >= 0 || j >= 0) {
int x = i>=0?(a[i]-48):0;
int y = j>=0?(b[j]-48):0;
int sum = x + y + carry;
result += to_string(sum % 2);
carry = sum>1?1:0;
i--;
j--;
}
if(carry) {
result += to_string(carry);
}
reverse(result.begin(), result.end());
return result;
}
};

Reference

  1. https://leetcode.com/problems/add-binary/description/
如果有收获,可以请我喝杯咖啡!