> For the complete documentation index, see [llms.txt](https://celia-qian.gitbook.io/leetcode-notebook-2020-2021/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://celia-qian.gitbook.io/leetcode-notebook-2020-2021/linear-list/array/plus-one.md).

# Plus One

## Plus One

原题链接：<https://leetcode.com/problems/plus-one/>

### 描述

> Given a **non-empty** array of digits representing a non-negative integer, increment 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 contains a single digit.
>
> You may assume the integer does not contain any leading zero, except the number 0 itself.

### 例子

> Input: digits = \[1,2,3]&#x20;
>
> Output: \[1,2,4]&#x20;
>
> Explanation: The array represents the integer 123.

### 解法一

[deque](http://cplusplus.com/reference/deque/deque/?kw=deque)

```cpp
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int n = digits.size();
        deque<int> dig;
        dig.assign(digits.begin(),digits.end());
	    for (int i = n - 1; i >= 0; --i)
	    {
		    if (dig[i] == 9)
		    {
			    dig[i] = 0;
                if(i==0){
                    dig.push_front(1);
                }
            }else{
                dig[i]++;
                break;
            }
	    }
        vector<int>res;
        res.assign(dig.begin(),dig.end());
        return res;
    }
};

```

### 解法二

```cpp
class Solution {
public:
    vector<int>plusOne(vector<int> &digits)
    {
	    int n = digits.size();
	    for (int i = n - 1; i >= 0; --i)
	    {
		    if (digits[i] == 9)
		    {
		    	digits[i] = 0;
		    }
		    else
		    {
		    	digits[i]++;
		    	return digits;
		    }
	    }
		digits[0] =1;
		digits.push_back(0);
    return digits;
	}
};
```

### 解法三

i[nsert](http://cplusplus.com/reference/vector/vector/insert/)

```cpp
class Solution {
public:
      vector<int> plusOne(vector<int> &digits) {
          add(digits, 1);
          return digits;
      }
private:
// 0 <= digit <= 9
    void add(vector<int> &digits, int digit) {
        int c = digit; // carry, 󿰤󿷰
        for (auto it = digits.rbegin(); it != digits.rend(); ++it) { 
            *it += c;
            c = *it / 10;
            *it %= 10; 
            }
        if (c > 0) digits.insert(digits.begin(), 1); 
        }
};
```
