LeetCode415. Add Strings

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.
class Solution {
public:
    string addStrings(string num1, string num2) {
        string ans="";
        int i=num1.size()-1,j=num2.size()-1;
        int sum=0;
        while(i>=0||j>=0)
        {
            int a=i>=0?num1[i--]-'0':0;
            int b=j>=0?num2[j--]-'0':0;
            sum+=a+b;
            ans.insert(ans.begin(),'0'+sum%10);
            sum/=10;
        }
        if(sum>0)
            ans.insert(ans.begin(),'0'+sum);
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/ueh286/article/details/93772688
今日推荐