File tree Expand file tree Collapse file tree 1 file changed +14
-23
lines changed Expand file tree Collapse file tree 1 file changed +14
-23
lines changed Original file line number Diff line number Diff line change 1-
2-
31/**
42 * Given a number represented as an array of digits, plus one to the number.
53 */
64
75public class PlusOne {
86 public int [] plusOne (int [] digits ) {
9- int advance = 0 ;
10- int i = digits .length - 1 ;
11- digits [i ] += 1 ;
12- do {
13- digits [i ] = digits [i ] + advance ;
14- if (digits [i ] >= 10 ) {
15- digits [i ] -= 10 ;
16- advance = 1 ;
17- } else {
18- advance = 0 ;
19- }
20- i --;
21- } while (advance != 0 && i >= 0 );
22- if (advance == 1 ) {
23- int [] result = new int [digits .length + 1 ];
24- result [0 ] = 1 ;
25- for (int j = 0 ; j < digits .length ; j ++) {
26- result [j + 1 ] = digits [j ];
27- }
28- return result ;
7+ int length = digits .length ;
8+ int add = 1 ;
9+ for (int i = length - 1 ; i >= 0 ; i --) {
10+ int sum = digits [i ] + add ;
11+ digits [i ] = sum % 10 ;
12+ add = sum / 10 ;
13+ if (add == 0 )
14+ return digits ;
15+ }
16+ int [] ret = new int [length + 1 ];
17+ ret [0 ] = add ;
18+ for (int i = 0 ; i < length ; i ++) {
19+ ret [i + 1 ] = digits [i ];
2920 }
30- return digits ;
21+ return ret ;
3122 }
3223}
You can’t perform that action at this time.
0 commit comments