[LeetCode] 989. Add to Array-Form of Integer

The array-form of an integer num is an array representing its digits in left to right order.

  • For example, for num = 1321, the array form is [1,3,2,1].

Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= num.length <= 104
  • 0 <= num[i] <= 9
  • num does not contain any leading zeros except for the zero itself.
  • 1 <= k <= 104

数组形式的整数加法。

整数的 数组形式  num 是按照从左到右的顺序表示其数字的数组。

例如,对于 num = 1321 ,数组形式是 [1,3,2,1] 。
给定 num ,整数的 数组形式 ,和整数 k ,返回 整数 num + k 的 数组形式 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-to-array-form-of-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这题跟[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[] num, int k) {
 3         int len = num.length;
 4         List<Integer> res = new ArrayList<>();
 5         
 6         int i = len - 1;
 7         int cur = k;
 8         while (i >= 0 || cur > 0) {
 9             if (i >= 0) {
10                 cur += num[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[]} num
 3  * @param {number} k
 4  * @return {number[]}
 5  */
 6 var addToArrayForm = function (num, k) {
 7     const len = num.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 += num[i];
14         }
15         res.push(cur % 10);
16         cur = parseInt(cur / 10);
17         i--;
18     }
19     return res.reverse();
20 };

 

LeetCode 题目总结

posted @ 2019-10-12 00:58  CNoodle  阅读(274)  评论(0编辑  收藏  举报