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.
Input a number, which is expressed as an array. The array is the number from high to low. Then the number is + 1; the returned result is.
The solution is case-based discussion. If there is no carry-in, it will be output directly. If there is an incoming bit and the array overflows, a new array will be returned.
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int oneplus=0; 4 for (int i = digits.length-1; i >=0; i--) { 5 if (digits[i]<9) { 6 digits[i]++; 7 oneplus=0; 8 break; 9 }else {10 oneplus=1;11 digits[i]=0;12 }13 }14 15 if (oneplus == 1) {16 int[] res = new int[digits.length+1];17 res[0]=1;18 for (int i = 1; i < res.length; i++) {19 res[i]=digits[i-1];20 }21 return res;22 }23 24 return digits;25 }26 }
Leetcode plus one