码迷,mamicode.com
首页 > 其他好文 > 详细

415. Add Strings

时间:2020-04-11 23:42:02      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:return   only   pre   turn   ted   must   length   strong   ++   

Problem:

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.

思路

Solution (C++):

string addStrings(string num1, string num2) {
    int m = num1.size() - 1, n = num2.size() - 1, carry = 0;
    string res = "";
    
    while (m >= 0 || n >= 0 || carry) {
        long long sum = 0;
        if (m >= 0)  { sum += (num1[m--]-‘0‘); }
        if (n >= 0)  { sum += (num2[n--]-‘0‘); }
        sum += carry;
        carry = sum / 10;
        sum %= 10;
        res += to_string(sum);
    }
    reverse(res.begin(), res.end());
    return res;
}

性能

Runtime: 8 ms??Memory Usage: 6.9 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

415. Add Strings

标签:return   only   pre   turn   ted   must   length   strong   ++   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12682901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!