当前位置:网站首页>Add one to non negative integers in the array

Add one to non negative integers in the array

2022-07-06 02:50:00 Xiao Qi,.

Give an array of integers to represent nonnegative integers , Add one to the number , And each array element only stores a single number , Divide integer 0 outside , This integer will not be expressed in 0 start .

for example :

Input :digits=[ 1,1,9 ]

Output :[ 1,2,0 ]

Input :digits=[ 9,9 ]

Output :[ 1,0,0 ]

Ideas : There are three situations

1. Not at the end 9 ,,, Add one directly to the end , Returns an array of

2. At the end is 9 ,,, Zero at the end , Traversal forward , Find out if 9 The elements of , Add one operation , Returns an array of

3. All the elements are 9,,, Reallocate the space of the array ( Add a space of shaping variables to the original space ), The first element is 1, All other elements belong to 0

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize){
    if(digits[digitsSize-1]!=9){ // Not at the end 9
        digits[digitsSize-1]++;
        *returnSize=digitsSize;
        return digits;
    }
    for(int i=digitsSize-1;i>=0;i--){ // At the end is 9
        if(digits[i]!=9){ // Find out if 9 The characters of , Add one operation 
            *returnSize=digitsSize;
            digits[i]++;
            return digits;
        }
        digits[i]=0; // If the character is 9, All become 0
    }
    *returnSize=digitsSize+1;// The characters in the array are all 9, Array needs to add one int Space occupied by type variables 
    digits=(int *)realloc(digits,*returnSize*sizeof(int));// Reallocate space 
    digits[digitsSize]=0;//
    digits[0]=1;
    return digits;
}

原网站

版权声明
本文为[Xiao Qi,.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132353464078.html