对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 {1,2,3,1}。(给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式)
示例:
输入:A = {2,1,5}, K = 806 输入:A = {9,9,9,9,9,9,9,9,9,9}, K = 1
输出:{1,0,2,1} 输出:1,0,0,0,0,0,0,0,0,0,0}
解释:215 + 806 = 1021 解释:9999999999 + 1 = 10000000000
提示:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
如果 A.length > 1,那么 A[0] != 0
/* Return an array of size *returnSize.
Note: The returned array must be malloced, assume caller calls free().
*/
int* addToArrayForm(int* A, int ASize, int K, int* returnSize) {
int m = ASize, t = 0;
int* res = (int*)malloc(sizeof(int)*(m + 4)); //考虑进位问题,申请内存存放新数组
for (int i = 0; i < m / 2; i++) { //逆置数组,数组的地位是整数的最高位
int tmp = A[i];
A[i] = A[m - 1 - i];
A[m - 1 - i] = tmp;
}
for (int i = 0; i < m; i++) {
K += A[i]; //整数的每一位加上数组的对应位
res[t++] = K % 10;
K /= 10;
}
while (K) {
res[t++] = K % 10; //考虑整数进位,补充最高位
K /= 10;
}
for (int i = 0; i < t / 2; i++) { //将数组逆置回来
int tmp = res[i];
res[i] = res[t - 1 - i];
res[t - 1 - i] = tmp;
}
*returnSize = t; //数组大小为t
return res;
}