-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path066. Plus One
64 lines (47 loc) · 1.64 KB
/
066. Plus One
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
核心是设置一个carry,
下面有一个更简洁的方法。如果你需要多出来一位比原先数组,基本意味着原来数组肯定全是9,99,999之类的。
所以index=0时 为1; 其余各位都为0.
public class Solution {
public int[] plusOne(int[] digits) {
boolean carry=false;
for(int i=digits.length-1;i>=0;i--){
if(i==digits.length-1||carry==true){//难点在这
if(digits[i]<9)
{digits[i]++;
carry=false;
break;
}
else{
digits[i]=0;
carry=true;
}
}
}
if(!carry){
return digits;
}
else
{ int[] result=new int[digits.length+1];
result[0]=1;
for (int i=1;i<digits.length+1;i++)
result[i]=digits[i-1];
return result;
}
}
}
public class Solution {
public int[] plusOne(int[] digits) {
for(int i=digits.length-1;i>=0;i--)
{if(digits[i]<9)
{digits[i]++;
return digits;
}
else
digits[i]=0;//这部更为精妙,因为它的逻辑是只要不是9,就+1,退出。如果是9;开始下一次循环,digit【i-1]要不是9,仍然加1;退出。。
否则接着下一次循环。如果最后都没return,只能说明原先数列里全是9.
}
int []numbers=new int[digits.length+1];
numbers[0]=1;
return numbers;
}
}