Lizou punching in 2021.1.22 integer addition in array form

Question:
For a non-negative integer X, the array form of X is an array formed by each digit from left to right. For example, if X = 1231, then its array form is [1,2,3,1].

Given the array form A of non-negative integer X, return the array form of 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

Code:

class Solution {
    
    
public:
    vector<int> addToArrayForm(vector<int>& A, int K) {
    
    
        // 反一下就是最小位了,好操作
        reverse(A.begin(), A.end());
        int t = K, idx=0;
        vector<int> ans;
        // 把能进的位都加进去
        while(t)
        {
    
    
            if(idx<A.size()) t+=A[idx++];
            ans.push_back(t%10);
            t /= 10;
        }
        // 把没进位的补上
        while(idx<A.size()) ans.push_back(A[idx++]);
        // 因为还是反的,再转回来
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112976422