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

61 lines
1.6 KiB
Markdown
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.

### leetcode 66 加一
**题目描述**
> 给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
>
> 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
>
> 你可以假设除了整数 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
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;
}
}
```