All Posts ←
← All Posts
Leetcode 989. Add to Array-Form of Integer
Tecker Yu
AI Native Cloud Engineer × Part-time Investor
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.
// Author: Tecker
// date: 2019.2.14
// 132ms, 13.3MB beat 99.19%, 100.00%
// time: O(N), space: O(1) or O(len(K))
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
// If the number represented by A is smaller than K (K max 10000)
if (A.size()<5) {
int t=1;
int sum=0;
for(int i=A.size()-1;i>=0;--i) {
sum+=A[i]*t;
t*=10;
}
// Direct conversion and addition, then modify A in place and return
sum+=K;
if (sum==0) return vector<int>{0};
// First insert from low to high digits at the back, then reverse
int pos=0;
while(sum!=0) {
if (pos>=A.size())
A.push_back(sum%10);
else
A[pos]=sum%10;
sum/=10;
++pos;
}
reverse(A.begin(), A.end());
return A;
}
// Directly add K to the lowest position, then propagate to higher positions
bool needMore = false;
for(int i=A.size()-1;i>=0;--i) {
A[i]+=K;
if (A[i] < 10) break;
if (i==0) needMore=true;
K=A[i]/10;
A[i]%=10;
}
if (!needMore) return A;
// Need to prepend 1
reverse(A.begin(), A.end());
A.push_back(1);
reverse(A.begin(), A.end());
return A;
}
};Key Insights
To insert elements at the beginning of a vector in place, you can first reverse it, add to the end, then reverse again.
Views