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

LeetCode 415. Add Strings

时间:2018-12-04 22:38:04      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:puts   library   rect   ted   for   lead   ring   represent   dir   

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

标签:puts   library   rect   ted   for   lead   ring   represent   dir   

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

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