LeetCode 415. Add Strings

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 415. Add Strings相关的知识,希望对你有一定的参考价值。

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

Note:

  • The length of both num1 and num2 is < 5100.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution {
public:
    string addStrings(string num1, string num2) {
        int max_len = max(num1.size(), num2.size());
        num1.insert(num1.begin(), max_len-num1.size(), '0');
        num2.insert(num2.begin(), max_len-num2.size(), '0');
        int t1=0, t2;
        string ans;
        for(int i=max_len-1; i>=0; i--){
            int t = t1;
            t1 =( (num1[i] - '0') + (num2[i] - '0') +t )/10;
            t2 =( (num1[i] - '0') + (num2[i] - '0') +t )%10;
            ans.insert(ans.begin(), 1, '0'+t2);
        }
        if(t1!=0)
            ans.insert(ans.begin(), 1, '0'+t1);
        return ans;
    }
};

以上是关于LeetCode 415. Add Strings的主要内容,如果未能解决你的问题,请参考以下文章

36. leetcode 415. Add Strings

leetcode 415. Add Strings

LeetCode 415. Add Strings

[leetcode-415-Add Strings]

LeetCode 415. Add Strings

leetcode练习:258. Add Digits & 415. Add Strings