> For the complete documentation index, see [llms.txt](https://quenluo.gitbook.io/leecode-python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://quenluo.gitbook.io/leecode-python/master.md).

# 066. Plus One

## Question 066

<https://leetcode.com/problems/plus-one/description/>

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.

for example\
input:\[1,2,3,4] >> output:\[1,2,3,5]\
input:\[1,3,0,0,9] >> output\[1,3,0,1,0]\
input:\[0] >> output:\[1]

### Answer&#x20;

### v1. switch to int first

1. 利用迴圈將 List 的位數依序乘上 10&#x20;
2. 將得出的整數 +1
3. 將整數除以 10 取餘數，並塞入新的 List 中
4. 將 List 以 .reverse() 反轉\
   ps. reverse() 並不會回傳值，而是直接對 List 本身做處理

### v2. use regression

1. 如果最後一位數小於 9 ， 只需將最後一位數 +1 。
2. 如果最後一位數為 9 ， 便需要做進位處理。

{% hint style="info" %}
要在 function 裡呼叫自己本身的所在的 function\
\==> *self.FunctionName()*&#x20;
{% endhint %}

{% tabs %}
{% tab title="v1 switch to int first" %}

```python
import math

class Solution(object):
    def plusOne(self, digits):
    
        AnsInt = 0
        Answer = []
    
        # switch to int
        for digit in digits:
            AnsInt = int(digit) + 10*AnsInt
        
        # plus one to int
        AnsInt += 1
        
        # switch back to List
        while AnsInt > 0 :
            Append_Temp = AnsInt % 10
            Answer.append(Append_Temp)
            AnsInt = AnsInt/10
        
        # The answer
        Answer.reverse()
        return Answer
```

{% endtab %}

{% tab title="v2 regression" %}

```python
import math

class Solution(object):
    def plusOne(self, digits):

        AnsInt = 0
        Answer = []
        
        if digits[-1] < 9 :
            if len(digits) > 1:
                return digits[:-1] + [digits[-1]+1]
            else :
                return [digits[-1]+1]
        else :
            if len(digits) > 1:
                return self.plusOne(digits[:-1]) + [0]
            else :
                return [1,0]
```

{% endtab %}
{% endtabs %}

welcome to check my Github \
**LeetCode-share(**[**https://github.com/QuenLo/LeeCode-share**](https://github.com/QuenLo/LeeCode-share)**)**
