力扣题-1.1
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:67. 二进制求和
解题思想:将数组进行遍历相加即可
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = a[::-1]
b = b[::-1]
i = 0
j = 0
flag = 0
temp = ''
while i<len(a) and j<len(b):
if (int(a[i])+int(b[j])+flag <=1):
temp += str(int(a[i])+int(b[j])+flag)
flag = 0
else:
temp += str(int(int(a[i])+int(b[j])+flag)%2)
flag = 1
i += 1
j += 1
while i<len(a):
if (int(a[i])+flag <=1):
temp += str(int(a[i])+flag)
flag = 0
else:
temp += str(int(int(a[i])+flag)%2)
flag = 1
i += 1
while j<len(b):
if (int(b[j])+flag <=1):
temp += str(int(b[j])+flag)
flag = 0
else:
temp += str(int(int(b[j])+flag)%2)
flag = 1
j +=1
if flag ==1:
temp +='1'
return temp[::-1]
class Solution {
public:
string addBinary(string a, string b) {
std::reverse(a.begin(), a.end());
std::reverse(b.begin(), b.end());
int i = 0, j = 0, flag = 0;
std::string result = "";
while (i < a.length() && j < b.length()) {
int sum = (a[i] - '0') + (b[j] - '0') + flag;
result += std::to_string(sum % 2);
flag = sum / 2;
i++;
j++;
}
while (i < a.length()) {
int sum = (a[i] - '0') + flag;
result += std::to_string(sum % 2);
flag = sum / 2;
i++;
}
while (j < b.length()) {
int sum = (b[j] - '0') + flag;
result += std::to_string(sum % 2);
flag = sum / 2;
j++;
}
if (flag == 1) {
result += '1';
}
std::reverse(result.begin(), result.end());
return result;
}
};