LeetCode 415 Add Strings

1643 ワード

タイトル:
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.

  • タイトルリンク
    タイトル:
    文字列で表される非負の数num 1とnum 2を2つ与え、この2つの数の和を返します.要件は4つあります.
  • num 1およびnum 2の長さはいずれも5100未満である.
  • num 1とnum 2はいずれも0-9
  • のみを含む.
  • num 1とnum 2はいずれも前置0
  • を含まない.
  • ライブラリ関数または変換関数
  • は使用できません.
    数の長さはlong longを使っても保存できないので、文字列シミュレーションで加算することを考えます.
    加減の過程で、常に文字が演算され、その関係をうまく処理します.
    コードは次のとおりです.
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            reverse(num1.begin(), num1.end());
            reverse(num2.begin(), num2.end());
            if (num1.length() < num2.length())
                swap(num1, num2);
            int up = 0;
            for (int i = 0; i < num1.length(); i++) {
                num1[i] += up;
                up = 0;
    
                if (i < num2.length()) {
                    num1[i] += num2[i] - '0';
                }
                while (num1[i] > '9') {
                    num1[i] -= 10;
                    up++;
                }
            }
            if (up) num1.push_back('0' + up);
            reverse(num1.begin(), num1.end());
            return num1;
        }
    };