# 66. Plus One

## 1.問題

* 給予一個list, 並在最末的數值+ 1, 問最終的list

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LN9kS56G2KEDfSdKvID%2F-LN9jB79b2L4DyriYVst%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-24%20%E4%B8%8B%E5%8D%884.40.21.png?alt=media\&token=f264123a-a196-4197-bf9c-6c400cecb3ba)

## 2.想法

* 提問: 確定是在第一個元素還是最末個元素+ 1
* function header, parameter
* test input
* 說明想法&#x20;
  * 因為在第一個元素+ 1會比較簡單, 因此計算前先對vector reverse以方便計算
  * 計算時須注意新的值是(carry + 自己) % 10, 並且更新carry
  * 當結束計算, carry不為零時, push到list中
  * reverse回來
* 測試計算複雜度

## 3.程式碼

```
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        //vector<int> res;
        reverse(digits.begin(), digits.end());
        int ret = 0, curr = 0; 
        for (int i = 0 ; i < digits.size(); i++){
            if( i == 0){
                ret = (digits[0] + 1) / 10;
                digits[0] = ((digits[0] + 1) < 10) ? digits[0] + 1 : (digits[0] + 1) % 10;
            }else{
                int t = digits[i];
                digits[i] = ((digits[i] + ret) < 10) ? digits[i] + ret : (digits[i] + ret) % 10;
                ret = (ret + t) / 10;
            }
        }
        if(ret != 0){
            digits.push_back(ret);
        }
        reverse(digits.begin(), digits.end());
        return digits;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/66.-plus-one.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
