p66

LeetCode p66 Plus One 题解

1.题目:

Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.

题意:

给你一个数组,这个数组从左到右排列代表一个数,比如[1,0].表示10.
现在给这个数加上一,返回加一之后形成的数组。比如[9] 返回[1,0].
(为什么我把题意解释的这么清楚呢,因为宛如智障的我看了好久题没看懂orz。

2.解题思路:

模拟加数进位,设置一个进位模拟的flag。从低位往高位遍历。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
public class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
int flag = 1;
for (int i = len - 1; i > -1; i--) {
if (digits[i] + flag == 10) {
flag = 1;
digits[i] = 0;
} else {
digits[i] += flag;
flag = 0;
}

}

if (flag == 1) {
int[] ans = new int[len + 1];
ans[0] = 1;
for (int i = 1; i < len + 1; i++) {
ans[i] = digits[i-1];
}
return ans;
} else {
return digits;
}
}
}

4.一些总结: