【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) {
        string ans;
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        int i=0,len1=num1.size();
        int j=0,len2=num2.size();
        int t=0;
        while(i<len1&&j<len2){
            int sum=t+(num1[i]-'0')+(num2[j]-'0');
            ans=(char)(sum%10+'0')+ans;
            t=sum/10;
            i++;j++;
        }
        while(i<len1){
            int sum=t+(num1[i]-'0');
            ans=(char)(sum%10+'0')+ans;
            t=sum/10;
            i++;
        }
         while(j<len2){
            int sum=t+(num2[j]-'0');
            ans=(char)(sum%10+'0')+ans;
            t=sum/10;
            j++;
        }
        if(t)ans='1'+ans;
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/a342500329a/article/details/77679631
今日推荐