Solution 1
和前一个题类似,这里也是进行加法逻辑的实现。区别在于这里是二进制,验证的过程相对复杂一些。其他的没有区别,也是需要注意一下最后一次加法运算的结果。
但是看了一下别人的题解,好像我这么写虽然也是模拟加法,但是好像很拧巴……
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n为输入较大字符串的长度,线性遍历
- 空间复杂度: O ( 1 ) O(1) O(1),只维护常数个状态变量,但是如果创建新字符串占用对应的空间
class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
string testa = a.size() > b.size() ? a : b;
string testb = a.size() <= b.size() ? a : b;
for (int i = testa.size() - 1; i >= 0; --i) {
int temp = 0;
if ((testa.size() - i) > testb.size()) {
temp = testa[i] - 48 + carry;
}
else {
temp = testa[i] - 48 + testb[testb.size() - (testa.size() - i)] - 48 + carry;
}
if (temp > 1) {
testa[i] = temp - 2 + 48;
carry = 1;
}
else {
testa[i] = temp + 48;
carry = 0;
}
}
string ans = testa;
if (carry == 1) {
ans = "1" + testa;
}
return ans;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def addBinary(self, a: str, b: str) -> str:
carry = 0
testa, testb = (list(a), list(b)) if len(a) > len(b) else (list(b), list(a))
for i in range(len(testa) - 1, -1, -1):
if len(testa) - i > len(testb):
temp = int(testa[i]) + carry
else:
temp = int(testa[i]) + int(testb[len(testb) - (len(testa) - i)]) + carry
if temp > 1:
testa[i] = str(temp - 2)
carry = 1
else:
testa[i] = str(temp)
carry = 0
ans = "".join(testa)
if carry == 1: ans = "1" + "".join(testa)
return ans