---
# System prepended metadata

title: 66. Plus One
tags: [math, Leetcode, python, c++, easy]

---

###### tags: `Leetcode` `easy` `math` `python` `c++`

# 66. Plus One

## [題目來源:] https://leetcode.com/problems/plus-one/

## 題目:
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.

## 解題想法:
1. 從尾加
1. 設carry判斷是否要進位

## Python:
``` python=
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        plus=1
        for i in range(len(digits)-1,-1,-1):
            if digits[i]+plus>9:
                digits[i]=0
                plus=1 #進位
            else:
                digits[i]+=plus
                plus=0
        #最左邊高位
        if plus==1:
            digits.insert(0,1) #(index,val)
        return digits


if __name__ == '__main__':
    result = Solution()
    digits = [4,3,2,1]
    ans = result.plusOne(digits)
    print(ans)
```

## C++:
``` cpp=
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    vector<int> plusOne(vector<int> &digits)
    {
        int plus = 1;
        for (int i = digits.size() - 1; i >= 0; i--)
        {
            if (digits[i] + plus > 9)
            {
                digits[i] = 0;
                plus = 1;
            }
            else
            {
                digits[i] += plus;
                plus = 0;
            }
        }
        if (plus == 1)
            digits.insert(digits.begin(), 1); //(position,val)
        return digits;
    }
};

int main()
{
    vector<int> digits = {1, 2, 3};
    Solution res;
    vector<int> ans = res.plusOne(digits);
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << ';';
    }
    cout << endl;
    return 0;
}
```