415. Add Strings 字符串相加

题目链接
tag:

  • easy

question:
  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.

思路:
  就是用两个String表示的数字,不用库的情况下实现加法。其实说白了就是高精度加法。从末尾开始相加,一位一位相加,然后算进位,最后根据进位情况看需不需要补一个高位,难度不大,参见代码如下:

class Solution {
public:
    string addStrings(string num1, string num2) {
        if (num1.size() < num2.size()) {
            string tmp = num1;
            num1 = num2;
            num2 = tmp;
        }
        int ai = num1.size()-1, bi = num2.size()-1, valueA = 0, valueB = 0, flag = 0;
        vector result;
        while (ai >= 0) {
            if (bi < 0) {
                valueB = 0;
            }
            else {
                valueB = num2[bi--] - 48;
            }
            valueA = num1[ai--] - 48;
            int sum = valueA + valueB + flag;
            flag = sum / 10;
            result.push_back(sum % 10);
        }
        if (flag == 1) {
            result.push_back(1);
        }  
        string output = "";
        vector::iterator it;
        for (it=result.begin(); it!=result.end(); ++it) {
            output += to_string(*it);
        }
        string _output(output.rbegin(), output.rend());  
        return _output;
    }
};

你可能感兴趣的:(415. Add Strings 字符串相加)