Skip to content

Commit 06c40b1

Browse files
committed
plusone
1 parent 0875226 commit 06c40b1

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

SUMMARY.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,8 @@
192192
- [Stone Game](/algorithm/LeetCode/Dynamic-Programming/Stone-Game.md)
193193
- [Array](/algorithm/LeetCode/Array.md)
194194
- [Partition Array](/algorithm/LeetCode/Array/Partition-Array.md)
195-
- [Subarray Sum](/algorithm/LeetCode/Array/Subarray-Sum.md)
195+
- [Subarray Sum](/algorithm/LeetCode/Array/Subarray-Sum.md)
196+
- [Plus One](/algorithm/LeetCode/Array/plus-one.md)
196197
- [String](/algorithm/LeetCode/String.md)
197198
- [Restore IP Addresses](/algorithm/LeetCode/String/ip.md)
198199

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## 一、题目
2+
3+
> Given a non-negative number represented as an array of digits, plus one to the number.
4+
>
5+
> The digits are stored such that the most significant digit is at the head of the list.
6+
>
7+
> Example
8+
>
9+
> Given [1,2,3] which represents 123, return [1,2,4].
10+
>
11+
> Given [9,9,9] which represents 999, return [1,0,0,0].
12+
13+
给一个包含非负整数的数组,其中每个值代表该位数的值,对这个数加1。
14+
15+
## 二、解题思路
16+
17+
1. 数组的最后一个数是个位数,所以从后面开始读,个位数+1后,如果有进位,存储进位值,没有直接存储。
18+
2. 处理十位数,如果个位数有进位,十位数+1,在判断十位数有没有进位。
19+
3. 重复上面的动作直到没有进位。
20+
21+
## 三、解题代码
22+
23+
```java
24+
public class Solution {
25+
26+
public int[] plusOne(int[] digits) {
27+
int carries = 1;
28+
for(int i = digits.length-1; i>=0 && carries > 0; i--){ // fast break when carries equals zero
29+
int sum = digits[i] + carries;
30+
digits[i] = sum % 10;
31+
carries = sum / 10;
32+
}
33+
if(carries == 0)
34+
return digits;
35+
36+
int[] rst = new int[digits.length+1];
37+
rst[0] = 1;
38+
for(int i=1; i< rst.length; i++){
39+
rst[i] = digits[i-1];
40+
}
41+
return rst;
42+
}
43+
}
44+
```
45+

0 commit comments

Comments
 (0)