码迷,mamicode.com
首页 > 其他好文 > 详细

Add to Array-Form of Integer LT989

时间:2019-04-05 09:24:39      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:res   nbsp   ||   ret   直接   lis   ide   lan   RKE   

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 }

 

Add to Array-Form of Integer LT989

标签:res   nbsp   ||   ret   直接   lis   ide   lan   RKE   

原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10657888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!