My first solution:
class Solution { public int[] plusOne(int[] digits) { int n = digits.length; int carry = 1; for(int i=n-1;i>=0;i--){ int digit = digits[i]; int sum = digit+carry; if(sum/10==0){ digits[i]=sum; return digits; }else{ digits[i]=sum%10; carry = sum/10; } } if(carry>0){ int[] res = new int[n+1]; res[0]=carry; for(int i=1;i<n+1;i++){ res[i]=digits[i-1]; } return res; } return digits; } }
The smarter solution and shorter solution:
class Solution { public int[] plusOne(int[] digits) { for(int i=digits.length-1;i>=0;i--){ if(digits[i]<9){ digits[i]++; return digits; } digits[i]=0; } int[] res = new int[digits.length+1]; res[0]=1; return res; } }