algorithm-base/animation-simulation/数组篇/leetcode66加一.md

126 lines
3.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [66. ](https://leetcode-cn.com/problems/plus-one/)
****
>
>
>
>
> 0
** 1**
> digits = [1,2,3]
> [1,2,4]
> 123
** 2**
> digits = [4,3,2,1]
> [4,3,2,2]
> 4321
** 3**
digits = [0]
[1]
****
****
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/加一.3lp9zidw61s0.png)
10
Java Code:
```java
class Solution {
public int[] plusOne(int[] digits) {
//获取长度
int len = digits.length;
for (int i = len-1; i >= 0; i--) {
digits[i] = (digits[i] + 1) % 10;
//第一种和第二种情况,如果此时某一位不为 0 ,则直接返回即可。
if (digits[i] != 0) {
return digits;
}
}
//第三种情况因为数组初始化每一位都为0我们只需将首位设为1即可
int[] arr = new int[len+1];
arr[0] = 1;
return arr;
}
}
```
Python Code:
```python
from typing import List
class Solution:
def plusOne(self, digits: List[int])->List[int]:
#
leng = len(digits)
for i in range(leng - 1, -1, -1):
digits[i] = (digits[i] + 1) % 10
# 0
if digits[i] != 0:
return digits
# 01
arr = [0] * (leng + 1)
arr[0] = 1
return arr
```
C++ Code:
```cpp
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for(int i = digits.size() - 1; i >= 0; --i){
digits[i] = (digits[i] + 1)%10;
if(digits[i]) return digits;
}
for(int & x: digits) x = 0;
digits.emplace_back(1);
reverse(digits.begin(), digits.end());
return digits;
}
};
```
Swift Code:
```swift
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
let count = digits.count
var digits = digits
for i in stride(from: count - 1, through: 0, by: -1) {
digits[i] = (digits[i] + 1) % 10
if digits[i] != 0 {
return digits
}
}
var arr: [Int] = Array.init(repeating: 0, count: count + 1)
arr[0] = 1
return arr
}
}
```