Leetcode 415. 字符串相加

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

  1. num1 和num2 的长度都小于 5100.
  2. num1 和num2 都只包含数字 0-9.
  3. num1 和num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

 

模拟竖式加法,注意这里的简洁实现方法,最后涉及到一个字符串反转

class Solution {
public:
    void reverse(string &s){
        int left=0,right=s.size()-1;
        while(left=0 || j>=0 ||carry!=0){
            if(i>=0)
                carry+=num1[i--]-'0';
            if(j>=0)
                carry+=num2[j--]-'0';
            res+= to_string(carry%10);
            carry/=10;
        }
        reverse(res);
        return res;
    }
};

 

你可能感兴趣的:(算法)