题目:



Given two non-negative integers ​​num1​​ and ​​num2​​ represented as string, return the sum of ​​num1​​ and ​​num2​​.

Note:

  1. The length of both 

​num1​

  1.  and 

​num2​

  1. Both 

​num1​

  1.  and 

​num2​

  1.  contains only digits 

​0-9​

  1. .
  2. Both 

​num1​

  1.  and 

​num2​

  1. You must not use any built-in BigInteger library or convert the inputs to integer

思路:

本题本质上十进制加法运算,满十进1,题目无非将数值转换成字符串,可以各位减‘0‘求得大小

代码:

class Solution {
public:
string addStrings(string num1, string num2) {
int i =num1.size()-1,j=num2.size()-1;
int carry = 0;
string res ="";
while(i>=0||j>=0||carry)
{
int sum = 0;
sum +=carry;
if(i>=0)
{
sum += (num1[i] - '0');
i--;
}
if(j>=0)
{
sum+=(num2[j] - '0');
j--;
}
carry = sum / 10;
sum = sum % 10;
res += to_string(sum);
}
reverse(res.begin(),res.end());
return res;
}
};