1/22 Lizou a daily question~Integer addition in array form

As the title~

For non-negative integer X, the array form of X is an array formed by each digit from left to right. For example, if X = 1231, then its array form is [1,2,3,1].
Given the array form A of non-negative integer X, return the array form of integer X+K.

Example 1:
Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:
Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:
Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:
Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0 ,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Tip:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
If A.length> 1, then A[0] != 0

Before I saw the prompt, I once thought about adding brute force!

but! Today I read the tips. . .

Then, go directly to the code.

//1.知道K的长度
//2.数组相加,逢十进一
//3.将数组翻转
int* addToArrayForm(int* A, int ASize, int K, int* returnSize) {
    
    
    if(K == 0 )
    {
    
    *returnSize = ASize;
        return A;
    }
    int Ksize = 0,a;//1.定义K的长度
    for(a=K;a>0;Ksize++)
    {
    
    
        a/=10;
    }
    int* returnX = malloc(sizeof(int) * fmax(Ksize+1, ASize + 1));//比较K和数组的长度谁长
    *returnSize = 0;//返回长度初始为0;
    for (int i = ASize - 1; i >= 0; --i) {
    
    //数组相加
        int sum = A[i] + K % 10;
        K /= 10;
        if (sum >= 10) {
    
    
            K++;
            sum -= 10;//2.开始逢十进一
        }
        returnX[(*returnSize)++] = sum;//一方面给returnSize++,一方面给数组数值
    }
    for (      ; K > 0; K /= 10) //这里如果K的长度大于了A的长度,K主导,再加!
    {
    
    
        returnX[(*returnSize)++] = K % 10;
    }
    for (int i = 0; i < (*returnSize) / 2; i++) //可以看出,咱们之前的都是倒序,该改过来了!
    {
    
    
        int c = returnX[i];
        returnX[i] = returnX[(*returnSize) - 1 - i];
        returnX[(*returnSize) - 1 - i] = c;
    }
    return returnX;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/FG_future/article/details/112982705