---
# System prepended metadata

title: 66. Plus One
tags: [LeetCode]

---

---
tags: LeetCode
---

# 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.    

自行測試 : 
Input: [9,9,9]    
Output: [1,0,0,0]    
Explanation: The array represents the integer 1000.    

輸入範本如下
```C#
public class Solution {
    public int[] PlusOne(int[] digits) {
    }
}
```

### 直覺想法
1. 在個位數加一後 , 檢查是否進位( 大於 9 ) , 若進位則 carry 設為 1 , digits[i] 取其個位數. 若無則 carry 設為 0 , digits[i] 一樣取其個位數
    ```C#
    240 ms	30.1 MB
    You are here!
    Your runtime beats 61.55 % of csharp submissions.
    public int[] PlusOne(int[] digits)
    {
        int carry = 1;
        for (int i = digits.Length - 1; i >= 0; i--)
        {
            int temp = (digits[i] + carry);
            digits[i] = temp % 10;
            carry = temp / 10;
        }

        if (carry == 0) // 無進位 , 直接回傳結果
        {
            return digits;
        }
        else // 進位 , 因為只加 1 , 所以高位數字必為 1 , 然後補零
        {
            int[] carryOneDigits = new int[digits.Length + 1];
            carryOneDigits[0] = 1;
            return carryOneDigits;
        }
    }
    ```

2. 加一後 , 若無進位 , 可以直接回傳結果 , 不必再繼續運算了.
    ```C#
    224 ms	29.8 MB
    You are here!
    Your runtime beats 98.79 % of csharp submissions
    public int[] PlusOne(int[] digits)
    {
        for (int i = digits.Length - 1; i >= 0; i--)
        {
            if (++digits[i] <= 9)
            {
                return digits;
            }
            else
            {
                digits[i] = 0; // 進位後 , 個位數必定為 0.
            }
        }

        int[] carryOneDigits = new int[digits.Length + 1];
        carryOneDigits[0] = 1;
        return carryOneDigits;
    }
    ```












### Thank you! 

You can find me on

- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)

若有謬誤 , 煩請告知 , 新手發帖請多包涵

# :100: :muscle: :tada: :sheep: 
