[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

整数相加。这题跟[LeetCode] 66. Plus One非常类似。题意是用一个数组A(表示了一个非负整数)和一个整数K的相加,求和并返回一个数组。我的思路是从数组的最右边的那一位开始每一位和K相加,把相加结果%10(其实也就是相加结果的个位数)放进res,最后再将res反转。注意K有可能有多个digit,需要额外判断是不是K == 0了再跳出while循环(Java第8行)。

时间O(n)

空间O(1) - 没有创造额外空间

Java实现

 1 class Solution {
 2     public List<Integer> addToArrayForm(int[] A, int K) {
 3         int len = A.length;
 4         int cur = K;
 5         List<Integer> res = new ArrayList<>();
 6 
 7         int i = len - 1;
 8         while (i >= 0 || cur > 0) {
 9             if (i >= 0) {
10                 cur += A[i];
11             }
12             res.add(cur % 10);
13             cur /= 10;
14             i--;
15         }
16         Collections.reverse(res);
17         return res;
18     }
19 }

JavaScript实现

 1 /**
 2  * @param {number[]} A
 3  * @param {number} K
 4  * @return {number[]}
 5  */
 6 var addToArrayForm = function(A, K) {
 7     const len = A.length;
 8     let cur = K;
 9     let res = [];
10     let i = len - 1;
11     while (i >= 0 || cur > 0) {
12         if (i >= 0) {
13             cur += A[i];
14         }
15         res.push(cur % 10);
16         cur = parseInt(cur / 10);
17         i--;
18     }
19     return res.reverse();
20 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11657987.html