Question:
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.
Answer:
public class Solution {public int[] plusOne(int[] digits) {int len=digits.length;
int index=-1;
for(int i=len-1;i>=0;i--){if(digits[i]!=9){
index=i;break;
}}if(index==-1){
int[] res=new int[digits.length+1];res[0]=1;return res;
}digits[index]++;for(int j=index+1;j<len;j++){digits[j]=0;}return digits;
}}
OR
public int[] plusOne(int[] digits) {int carry = 1;
for (int i = digits.length-1; i>= 0; i--) {digits[i] += carry;if (digits[i] <= 9) // early returnreturn digits;
digits[i] = 0;}int[] ret = new int[digits.length+1];ret[0] = 1;return ret;
}