← Home

989. Add to Array-Form of Integer

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
989

Let's make this one less mysterious. For 989. Add to Array-Form of Integer, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are addToArrayForm.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 116 ms, faster than 99.24% of C++ online submissions for Add to Array-Form of Integer.
02//Memory Usage: 12.2 MB, less than 100.00% of C++ online submissions for Add to Array-Form of Integer.
03
04class Solution {
05public:
06    vector<int> addToArrayForm(vector<int>& A, int K) {
07        int cur = 0;
08        int N = A.size();
09        
10        //add K to A
11        while(K > 0){
12            int cursum;
13            //current digit
14            if(N-1-cur >= 0){
15                cursum = A[N-1-cur]+K%10;
16                A[N-1-cur] = cursum%10;
17            }else{
18                cursum = K%10;
19                A.insert(A.begin(), cursum);
20                //now the size of A changes
21                N++;
22            }
23            //carry over
24            if(N-1-(cur+1) >= 0){
25                //just update the higher digit
26                A[N-1-(cur+1)] += cursum/10;
27            }else if(cursum/10 > 0){
28                //need one more digit
29                A.insert(A.begin(), cursum/10);
30                N++;
31            }
32            K/=10;
33            cur++;
34        }
35        //deal with carry over
36        while(N-1-cur >= 0 && A[N-1-cur] >= 10){
37            int tmp = A[N-1-cur];
38            //current digit
39            A[N-1-cur] = tmp%10;
40            //deal with carry over
41            if(N-1-(cur+1) >= 0){
42                A[N-1-(cur+1)] += tmp/10;
43            }else{
44                A.insert(A.begin(), tmp/10);
45            }
46            cur++;
47        }
48        return A;
49    }
50};
51
52/**
53Approach 1: Schoolbook Addition
54Intuition
55
56Let's add numbers in a schoolbook way, column by column. For example, to add 123 and 912, we add 3+2, then 2+1, then 1+9. Whenever our addition result is more than 10, we carry the 1 into the next column. The result is 1035.
57
58Algorithm
59
60We can do a variant of the above idea that is easier to implement - we put the entire addend in the first column from the right.
61
62Continuing the example of 123 + 912, we start with [1, 2, 3+912]. Then we perform the addition 3+912, leaving 915. The 5 stays as the digit, while we 'carry' 910 into the next column which becomes 91.
63
64We repeat this process with [1, 2+91, 5]. We have 93, where 3 stays and 90 is carried over as 9. Again, we have [1+9, 3, 5] which transforms into [1, 0, 3, 5].
65**/
66
67/**
68Complexity Analysis
69
70Time Complexity: O(\max(N, \log K))O(max(N,logK)) where NN is the length of A.
71
72Space Complexity: O(\max(N, \log K))O(max(N,logK)). 
73**/
74
75//Runtime: 116 ms, faster than 99.24% of C++ online submissions for Add to Array-Form of Integer.
76//Memory Usage: 13.7 MB, less than 52.65% of C++ online submissions for Add to Array-Form of Integer.
77/**
78class Solution {
79public:
80    vector<int> addToArrayForm(vector<int>& A, int K) {
81        int N = A.size();
82        vector<int> ans;
83        
84        int i = N-1;
85        //exit when both A and K are visited through
86        while(i >= 0 || K > 0){
87            if(i >= 0) K += A[i];
88            ans.push_back(K%10);
89            K/=10;
90            i--;
91        }
92        
93        reverse(ans.begin(), ans.end());
94        
95        return ans;
96    }
97};
98**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.