|
| 1 | +package easy; |
| 2 | + |
| 3 | +import utils.CommonUtils; |
| 4 | + |
| 5 | +/**66. Plus One QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 115402 |
| 7 | +Total Submissions: 328650 |
| 8 | +Difficulty: Easy |
| 9 | +Given a non-negative number represented as an array of digits, plus one to the number. |
| 10 | +
|
| 11 | +The digits are stored such that the most significant digit is at the head of the list.*/ |
| 12 | +public class PlusOne { |
| 13 | + //also looked at Discuss, basically the same idea as mine, just their code is more concise. |
| 14 | + |
| 15 | + public int[] plusOne(int[] digits) { |
| 16 | + boolean carry = false; |
| 17 | + int len = digits.length; |
| 18 | + int[] temp = digits; |
| 19 | + //process the last digit at first, to get carry value |
| 20 | + if(digits[len-1] + 1 == 10) { |
| 21 | + carry = true; |
| 22 | + temp[len-1] = 0; |
| 23 | + } |
| 24 | + else { |
| 25 | + temp[len-1] += 1; |
| 26 | + return temp; |
| 27 | + } |
| 28 | + |
| 29 | + //start from the second last element |
| 30 | + for(int i = len-2; i >= 0; i--){ |
| 31 | + if(carry && temp[i] + 1 == 10){ |
| 32 | + temp[i] = 0; |
| 33 | + carry = true; |
| 34 | + } else if(carry) { |
| 35 | + temp[i] += 1; |
| 36 | + carry = false; |
| 37 | + } |
| 38 | + } |
| 39 | + if(carry && temp[0] == 0) { |
| 40 | + int[] res = new int[len+1]; |
| 41 | + res[0] = 1; |
| 42 | + //all the rest of the numbers should all be zeroes, so we don't need to copy from the original array |
| 43 | + return res; |
| 44 | + } |
| 45 | + return temp; |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String...strings){ |
| 49 | + PlusOne test = new PlusOne(); |
| 50 | +// int[] digits = new int[]{9,9,9,9}; |
| 51 | +// int[] digits = new int[]{8,9,9,9}; |
| 52 | + int[] digits = new int[]{2,4,9,3,9}; |
| 53 | + int[] res = test.plusOne(digits); |
| 54 | + CommonUtils.printArray(res); |
| 55 | + } |
| 56 | +} |
0 commit comments