---
# System prepended metadata

title: LeetCode 66. Plus One
tags: [Leetcode]

---

---
title: 'LeetCode 66. Plus One'
disqus: hackmd
---

# LeetCode 66. Plus One



## Description

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

## Example

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

## Constraints

1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.

## Answer

視最高位是多少就開多大的memory，若開頭為9就開原size+1個memory，用for檢查高到低位，每次計算當下值和進位值，直到所有項目檢查完後要看有無最高位進位，若有接給定為1，若無還須調整最高位為9的returnSize及ans開頭address，因不需要進位就要將原本多給的memory或size扣回去。

```Cin=
//2022_03_30
int* plusOne(int* digits, int digitsSize, int* returnSize){
    int i = 0, size = 0, pls = 1;
    size = digits[0] == 9 ? digitsSize+1 : digitsSize;
    int *ans = (int*)malloc(sizeof(int)*size);
    *returnSize = size;
    size--;
    for(i = digitsSize-1; i >= 0; i--,size--){
        ans[size] = (digits[i] + pls) % 10;
        pls = (digits[i] + pls) / 10;
    }
    if(size == 0){
        if(pls){ans[size] = 1;}
        else{ans++; (*returnSize)--;}
    }
    return ans;
}
```



## Link
https://leetcode.com/problems/plus-one/
###### tags: `Leetcode` 
