415. Add Strings

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 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

 给定两个非负整数用字符串表示的非负整数num1和num2,求它们的和。
 
分析:
  这题比较简单,将num1、num2按位相加,并计算进位即可。
代码如下:
string addStrings(string num1, string num2)
{
    string rst;
    reverse(num1.begin(), num1.end());
    reverse(num2.begin(), num2.end());
    int len1 = num1.length();
    int len2 = num2.length();
    int len = len1 > len2 ? len1 : len2;
    char last = 0;
    for (int i = 0; i < len; i++)
    {
        char ch = last;
        if (i < len1)
            ch += (num1[i] - '0');
        if (i < len2)
            ch += (num2[i] - '0');
        last = ch / 10;
        ch %= 10;
        rst += (ch + '0');
    }
    if (last > 0)
        rst += (last + '0');
    reverse(rst.begin(), rst.end());
    return rst;
}
 

猜你喜欢

转载自www.cnblogs.com/big-potato/p/9036045.html
今日推荐