/*
问题描述:Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2
来源:LintCode
作者:syt
问题描述:Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2
来源:LintCode
作者:syt
日期:2017-7-16
思路:写了两个方法,但大致差不多,基本思路就是取出字符串中的数相加,需要注意低位进位和最高位的进位,感觉应该有更加简单的方法,继续思考
*/
#include <iostream>
#include <string>
using namespace std;
class AddStrings{
public:
/**
* @param num1 a non-negative integers
* @param num2 a non-negative integers
* @return return sum of num1 and num2
*/
//方法1
string addStrings1(string& num1, string& num2) {
// Write your code here
if (num1.length() < num2.length())
{
string tmp = num1;
num1 = num2;
num2 = tmp;
}
int len1 = num1.length() - 1;
int len2 = num2.length() - 1;
string result = "";
bool is = false; //处理进位
while (len1 >= 0 && len2 >= 0)
{
int tmp1 = num1[len1] - 48;
int tmp2 = num2[len2] - 48;
int tmp = tmp1 + tmp2;
if (is)
tmp++;
if (tmp >= 10)
{
is = true;
tmp = tmp - 10;
}
else
is = false;
result = to_string(tmp) + result;
len1--;
len2--;
}
while (len1 >= 0)
{
int tmp = num1[len1] - 48;
if (is)
tmp++;
if (tmp >= 10)
{
is = true;
tmp = tmp - 10;
}
else
is = false;
result = to_string(tmp) + result;
len1--;
}
if (is)
result = "1" + result;
return result;
}
//方法2
string addStrings(string& num1, string& num2) {
// Write your code here
if (num1.length() < num2.length())
{
string tmp = num1;
num1 = num2;
num2 = tmp;
}
int len2 = num2.length() - 1;
int len = num1.length() - 1;
bool is = false;
while (len2 >= 0)
{
int tmp = num1[len] + num2[len2] - 96;
if (is)
tmp++;
if (tmp >= 10)
{
is = true;
tmp = tmp - 10;
}
else
is = false;
//cout << tmp << endl;
num1[len] = tmp + 48;
len--;
len2--;
}
while (len >= 0)
{
int tmp = num1[len] - 48;
if (is)
tmp++;
if (tmp >= 10)
{
is = true;
tmp = tmp - 10;
}
else
is = false;
num1[len] = tmp + 48;
len--;
}
if (is)
num1 = "1" + num1;
return num1;
}
};