66.Plus One
Given a non-negative integer represented as anon-emptyarray of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
class Solution {
// 999 -> 1000
public int[] plusOne(int[] digits) {
if (digits == null) {
return new int[0];
}
if (digits.length == 0) {return digits;}
int sum = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int temp = digits[i] + sum;
digits[i] = temp % 10;
sum = temp / 10;
}
if (sum != 0) {
int[] ans = new int[digits.length + 1];
ans[0] = sum;
for (int i = 0; i < digits.length; i++) {
ans[i+1] = digits[i];
}
return ans;
}else{
return digits;
}
}
}