[LeetCode] 989. Add to Array-Form of Integer 數組形式的整數加法



For a non-negative integer X, the array-form of X is an array of its digits in left to right order.  For example, if X = 1231, then the array form is [1,2,3,1].

Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.

Example 1:

Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:

Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Note:

  1. 1 <= A.length <= 10000
  2. 0 <= A[i] <= 9
  3. 0 <= K <= 10000
  4. If A.length > 1, then A[0] != 0

這道題給了一個數組A,說是可以表示一個正整數,高位在開頭,又給了一個正數K,讓用數組A表示的正整數加上K,並還用數組來表示相加的后的結果。這種用不同的數據結構玩加法的題,之前也出現過,比如 Add Two NumbersPlus OneAdd Binary,和 Add Strings。但其實都是萬變不離其宗,都是要一位一位的相加,並且處理好進位的問題。這里由於高位是在數組開頭,而相加是要從低位開始的,所以從數組的后面往前開始遍歷,用當前位上的數字加上K,再對 10 取余,得到的就是相加后該位上的數字。大家可能會擔心進位的問題,進位后的結果會被加到K中,不會丟失,此時K再加上了 A[i] 之后也應該除以 10,然后繼續進行循環。當數組A遍歷完后,K可能還大於0,此時的K值就應該以數組的形式加到前頭,每次將對 10 取余的值加到結果 res 開頭,然后K自除以 10 即可,參見代碼如下:


解法一:

class Solution {
public:
    vector<int> addToArrayForm(vector<int>& A, int K) {
        vector<int> res;
        for (int i = (int)A.size() - 1; i >= 0; --i) {
            res.insert(res.begin(), (A[i] + K) % 10);
            K = (A[i] + K) / 10;
        }
        while (K > 0) {
            res.insert(res.begin(), K % 10);
            K /= 10;
        }
        return res;
    }
};

當然我們也可以只用一個循環搞定,並且直接更新數組A,不額外使用數組。那么循環條件就是K大於0,或進位值 carry 大於0。在循環中,先讓 carry 加上K對 10 取余的值,此時若數組A的值還沒有遍歷完,即i大於等於0時,再加上 A[i],此時 num 除以 10 就是更新后的 carry 值,對 10 取余就是當前位上的值。此時若i大於等於0,則更新 A[i] 為 num 值,且i自減1,否則將 num 加到數組A的開頭,然后K在自除以 10,最后返回數組A即可,參見代碼如下:


解法二:

class Solution {
public:
    vector<int> addToArrayForm(vector<int>& A, int K) {
		int n = A.size(), i = n - 1, carry = 0;
		while (K > 0 || carry > 0) {
			int num = K % 10 + carry;
			if (i >= 0) num += A[i];
			carry = num / 10;
			num %= 10;
			if (i >= 0) {
				A[i] = num;
				--i;
			} else {
				A.insert(A.begin(), num);
			}
			K /= 10;
		}
		return A;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/989


類似題目:

Add Two Numbers

Plus One

Add Binary

Add Strings


參考資料:

https://leetcode.com/problems/add-to-array-form-of-integer/

https://leetcode.com/problems/add-to-array-form-of-integer/discuss/234488/JavaC%2B%2BPython-Take-K-itself-as-a-Carry

https://leetcode.com/problems/add-to-array-form-of-integer/discuss/234558/JavaPython-3-6-liner-w-comment-and-analysis


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM