leetcode 989. 数组形式的整数加法(Add to Array-Form of Integer)
题目描述:
对于非负整数 X
而言,X
的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231
,那么其数组形式为 [1,2,3,1]
。
给定非负整数 X
的数组形式 A
,返回整数 X+K
的数组形式。
示例 1:
输入:A = [1,2,0,0], K = 34
输出:[1,2,3,4]
解释:1200 + 34 = 1234
示例 2:
输入:A = [2,7,4], K = 181
输出:[4,5,5]
解释:274 + 181 = 455
示例 3:
输入:A = [2,1,5], K = 806
输出:[1,0,2,1]
解释:215 + 806 = 1021
示例 4:
输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1
输出:[1,0,0,0,0,0,0,0,0,0,0]
解释:9999999999 + 1 = 10000000000
提示:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
- 如果
A.length > 1
,那么A[0] != 0
解法:
class Solution {
public:
vector<int> parse(int num){
vector<int> res;
if(num == 0){
res.push_back(0);
}else{
while(num != 0){
res.insert(res.begin(), num%10);
num /= 10;
}
}
return res;
}
vector<int> addToArrayForm(vector<int>& A, int K) {
vector<int> delta = parse(K);
// for(int val : delta){
// cout<<val<<"\t";
// }
// cout<<endl;
int sz1 = A.size(), sz2 = delta.size();
int sz = max(sz1, sz2);
vector<int> res(sz, 0);
int i = sz1-1, j = sz2-1, idx = sz-1;
int carry = 0;
while(i >= 0 && j >= 0){
int digit = A[i] + delta[j] + carry;
if(digit >= 10){
carry = 1;
digit -= 10;
}else{
carry = 0;
}
res[idx] = digit;
i--;
j--;
idx--;
}
while(i >= 0){
int digit = A[i] + carry;
if(digit >= 10){
carry = 1;
digit -= 10;
}else{
carry = 0;
}
res[idx] = digit;
i--;
idx--;
}
while(j >= 0){
int digit = delta[j] + carry;
if(digit >= 10){
carry = 1;
digit -= 10;
}else{
carry = 0;
}
res[idx] = digit;
j--;
idx--;
}
if(carry != 0){
res.insert(res.begin(), carry);
}
return res;
}
};