LeetCode:989. Add to Array-Form of Integer陣列形式的整數加法(C語言)
阿新 • • 發佈:2021-02-01
技術標籤:LeetCode
題目描述:
對於非負整數 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
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/add-to-array-form-of-integer
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
解答:
int* addToArrayForm (int* A, int ASize, int K, int* returnSize){
int len = fmax(ASize, 5) + 1;
int *res = (int*)malloc(sizeof(int) * len);
int i = ASize - 1;
int idx = 0;
while (K != 0 || i >= 0) {
K += (i >= 0) ? A[i--] : 0;
res[--len] = K % 10;
K /= 10;
idx++;
}
*returnSize = idx;
return res + len;
}
執行結果: