首页 > 其他 > 详细

LeetCode 415. Add Strings

时间:2018-12-04 21:46:21      阅读:169      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/A-Little-Nut/p/10066921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!