Add to Array-Form of Integer LT989

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

 Idea 1: 大数的相加

Time complexity: O(max(n, log(K))), n = A.length

Space complexity: O(max(n, log(K)))

 1 class Solution {
 2     public List<Integer> addToArrayForm(int[] A, int K) {
 3         List<Integer> result = new ArrayList<>();
 4         int carry = 0;
 5         
 6         for(int left = A.length-1, curr = K; left >= 0 || curr != 0 || carry != 0; --left) {
 7             int val1 = left >= 0? A[left] : 0;
 8             int val2 = curr%10;
 9             int sum = val1 + val2 + carry;
10             result.add(sum%10);
11             carry = sum/10;
12             curr = curr/10;
13         }
14         
15         Collections.reverse(result);
16         return result;
17     }
18 }

Idea 1.a 网上的解法,代码更简洁,少用carry这个变量,直接用K加数组里的每个数字

Note. 如果K是Integer.MAX_VALUE, 这样加会overflow

A= {1, 2, 9, 9}, K = 99

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

 

上一篇:67. Add Binary


下一篇:《剑指offer》第六十五题(不用加减乘除做加法)