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.
public class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length -1 ; i >= 0; i--) {
digits[i] += 1;
if(digits[i] < 10)
break;
digits[i] = 0;
}
if(digits[0] == 0){
int[] ans = new int[digits.length+1];
ans[0] = 1;
ans[digits.length] = 0;
for (int j = 0; j < digits.length; j++) {
ans[j+1] = digits[j];
}
return ans;
}
return digits;
}
The main point is pretty simple. But the if phrase is still smart in the first loop.