Add to Array-Form of Integer
Add to Array-Form of Integer
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 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;
}
// Convert and add directly, then modify A in place
sum+=K;
if (sum==0) return vector<int>{0};
// Insert low to high digits first, 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;
}
// Add K directly to lowest digit, then propagate to highest digit
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;
// Prepend 1
reverse(A.begin(), A.end());
A.push_back(1);
reverse(A.begin(), A.end());
return A;
}
};Key Insight
To insert elements at the beginning of a vector in place, reverse it first, append at the end, then reverse again.