0
点赞
收藏
分享

微信扫一扫

LeetCode-67. Add Binary

gy2006_sw 2022-08-10 阅读 69


Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters ​​1​​​ or ​​0​​.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

题解:

class Solution {
public:
string add(string a, string b, int n) {
string s;
int plus = 0;
for (int i = n - 1; i >= 0; i--) {
int num = plus + a[i] + b[i] - 96;
if (num < 2) {
s.insert(s.begin(), num + 48);
plus = 0;
}
else {
s.insert(s.begin(), num + 46);
plus = 1;
}
}
if (plus == 1) {
s.insert(s.begin(), '1');
}
return s;
}
string addBinary(string a, string b) {
int n = a.length(), m = b.length();
if (n < m) {
for (int i = 0; i < m - n; i++) {
a.insert(a.begin(), '0');
}
}
else if (n > m) {
for (int i = 0; i < n - m; i++) {
b.insert(b.begin(), '0');
}
}
return add(a, b, max(n, m));
}
};

 

举报

相关推荐

0 条评论