2016年2月13日 星期六

LEET code -- Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

把int陣列+1
digits[0]是最高位
要注意memcpy是要用sizeof去算的 跟malloc一樣




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize) {
    int carrier=0;
    if(digits[digitsSize-1]+1>=10){
        carrier=1;
        digits[digitsSize-1]=0;
        for(int i =digitsSize-2;i>=0;i--){
            if(digits[i]+carrier>=10){
                carrier=1;
                digits[i]=0;
            }else{
                digits[i]+=1;
                carrier=0;
                break;
            }
        }
    }else{
        digits[digitsSize-1]+=1;
    }
    
    int *ans;
    if(digits[0]==0 && carrier==1){
        //overflow
        ans=malloc(sizeof(int)*(digitsSize+1));
        memcpy(ans+1,digits,digitsSize*sizeof(int));
        ans[0]=1;
        *returnSize=digitsSize+1;
    }else{
        ans=malloc(sizeof(int)*digitsSize);
        memcpy(ans,digits,digitsSize*sizeof(int));//need to be sizeof(int)
        *returnSize=digitsSize;
    }
    return ans;
}



------------------
但是可以再縮短
carrier一開始設1


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize) {
    int carrier=1;
    for(int i =digitsSize-1;i>=0;i--){
        if(digits[i]+carrier>=10){
            carrier=1;
            digits[i]=0;
        }else{
            digits[i]+=1;
            carrier=0;
            break;
        }
    }

    int *ans;
    if(digits[0]==0 && carrier==1){
        //overflow
        ans=malloc(sizeof(int)*(digitsSize+1));
        memcpy(ans+1,digits,digitsSize*sizeof(int));
        ans[0]=1;
        *returnSize=digitsSize+1;
    }else{
        ans=malloc(sizeof(int)*digitsSize);
        memcpy(ans,digits,digitsSize*sizeof(int));//need to be sizeof(int)
        *returnSize=digitsSize;
    }
    return ans;
}

沒有留言:

張貼留言