67. 二进制求和 - 力扣(LeetCode)
两个题目方法完全一样
用两个数据的末尾位相加,从末尾位开始逐位相加,记录进位;
class Solution {
public:
string addBinary(string a, string b) {
int end1 = a.size() - 1;
int end2 = b.size() - 1;
string num;//最终的结果
int next = 0;//进位
while(end1 >= 0 || end2 >= 0)
{
int val1 = 0, val2 = 0;
if(end1 >= 0)
val1 = a[end1] - '0';
if(end2 >= 0)
val2 = b[end2] - '0';
int sum = val1 + val2 + next;
if(sum > 1)
{
sum -= 2;
next = 1;
}
else
{
next = 0;
}
num.push_back(sum + '0');
end1--;
end2--;
}
if(next == 1)
{
num.push_back('1');
}
reverse(num.begin(),num.end());
return num;
}
};
reverse是stl里面的算法,就是逆置;
+=都是头插;
方法是先用个位相加,然后有进位的标记;
其中首先他是字符所以减去'0',ascll码相减就会变成能加减的数值,最后还要转变回来,所以+'0'
415. 字符串相加 - 力扣(LeetCode)
class Solution {
public:
string addStrings(string num1, string num2) {
int end1 = num1.size() - 1;
int end2 = num2.size() - 1;
string retstr;
int next = 0;//进位
while(end1 >= 0 || end2 >= 0)
{
int val1 = 0, val2 = 0;
if(end1 >= 0)
val1 = num1[end1] - '0';//字符串相减
if(end2 >= 0)
val2 = num2[end2] - '0';
int ret = val1 + val2 + next;
if(ret > 9)
{
ret -= 10;
next = 1;
}
else
{
next = 0;
}
retstr += (ret + '0');
--end1;
--end2;
}
if(next == 1){
retstr += "1";
}
reverse(retstr.begin(), retstr.end());
return retstr;
}
};