LeetCode 66. Plus One(加一) -- c语言

66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

解题思路:

从最后一个元素开始,有进位时向高位相加,无进位时直接退出。最后还有进位时则需重新开辟返回数组result为n+1个数组空间

/*执行用时 : 8 ms, 在Plus One的C提交中击败了93.82% 的用户
内存消耗 : 7.1 MB, 在Plus One的C提交中击败了5.51% 的用户
*/

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize){

    *returnSize = digitsSize;
    int i=0;
    
    //记录进位,初始进位为1,因为要加一,相当于在低位有一个进位
    int curr=1;
    
    for(i=digitsSize-1;i>=0;i--){
        
        curr=(digits[i]+curr)/10;//当前元素进位
        
        if(curr==0){
            //进位为0代表无需再加了
            digits[i]+=1;
            break;
        }
        else{
            //有进位时当前元素为0,转向处理高位
            digits[i]=0;
        }
    }
    
    if(curr!=0){
        
        //有进位时需重新定义一个大小为digitsSize+1的返回数组
        int *result = (int *)malloc((digitsSize+1)*sizeof(int));
        
        //将结果赋值給返回数组
        for(i=digitsSize-1;i>=0;i--){
          result[i+1]=digits[i];
        }
        result[0]=curr;
        
        //设置返回数组大小
       *returnSize=digitsSize+1;
        
        return result;
    }
    else{
        return digits;
    } 
}

后记:

若有进位时用digits返回,数组大小为digitsSzie,但需返回digitsSize+1,下标溢出,此时应新定义一个大小为digitsSize+1的返回数组。

你可能感兴趣的:(LeetCode,(力扣),C语言,算法,(Algorithm),数据结构,(Data,Structure),LeetCode,66,Plus,One,加一,c语言)