Leetcode 415 题
Difficulty:Easy
Tag: Math
Add strings
原题目链接:https://leetcode.com/problems/add-strings/?tab=Description
字符串相加。 原理同 leetcode002
注意
string to int 和 int to string的转换
class Solution {
public:
string addStrings(string num1, string num2) {
int index1 = num1.length() - 1;
int index2 = num2.length() - 1;
int carry = 0;
string output = "";
while(index1 >= 0 || index2 >= 0 || carry)
{
int result = 0;
if(index1 >= 0)
{
result += num1[index1] - '0';
index1--;
}
if(index2 >= 0)
{
result += num2[index2] - '0';
index2--;
}
result += carry;
carry = result / 10;
result = result % 10;
char a = result + '0';
output = output + a;
}
reverse(output.begin(), output.end());
return output;
}
};