主接口addstring,在内部根据不同的情况调用doublePositive()和minusstring(),
需要注意的地方都写在注释里了
string doublePositive(string s1, string s2)
{
int l1 = s1.size()-1, l2 = s2.size()-1;
string res;
int jinwei = 0;
while (l1 >= 0 || l2 >= 0)
{
int a = (l1 >= 0 ? s1[l1--] - '0' : 0);
int b = (l2 >= 0 ? s2[l2--] - '0' : 0);
int sum = a + b + jinwei;
res = to_string(sum % 10) + res;
jinwei = sum / 10;
}
if (jinwei)
res = '1' + res;
return res;
}
string minusstring(string s1, string s2)//s1,s2都为正,且s1大于s2
{
int l1 = s1.size() - 1, l2 = s2.size() - 1;
string res;
while (l1 >= 0 || l2 >= 0)
{
int a = l1 >= 0 ? s1[l1--] - '0' : 0;
int b = l2 >= 0 ? s2[l2--] - '0' : 0;
int tmp = a - b;
if (tmp < 0)
{
tmp += 10;
s1[l1]--;
}
res = to_string(tmp) + res;
}
if (res[0] == '0')//考虑首位的1被借,则为0
res.erase(0, 1);
return res;
}
string addstring(string s1, string s2)
{
if (s1.empty())
return s2;
if (s2.empty())
return s1;
if (s1[0] != '-' && s2[0] != '-')//都为正
return doublePositive(s1, s2);
if (s1[0] == '-' && s2[0] == '-')//都为负
return "-" + doublePositive(s1.erase(0, 1), s2.erase(0, 1));
if (s1[0] == '-')
return addstring(s2, s1);
s2.erase(0, 1);//比较s1和s2的绝对值
if (s1.size() > s2.size())
return minusstring(s1, s2);
else if (s1.size() < s2.size())
return "-" + minusstring(s2, s1);
else
{
for (int i = 0; i < s1.size(); i++)
{
if(s1[i] < s2[i])
return "-" + minusstring(s2, s1);
else if(s1[i] > s2[i])
return minusstring(s1, s2);
}
}
return "0";//s1,s2对应的每一位都相等
}