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.
没什么难点,若末位不是9,则末位直接加1返回。若末位是9,则置零,从末位开始向前判断,直到遇到不是9的数加一返回。注意若数组长度不为2且最高位被置零,则要重新 new 一个多一位的数组并把最高位置一。代码如下:
public class Solution {
public int[] plusOne(int[] digits) {
int carry = 0;
for(int i = digits.length - 1; i >= 0; i--) {
if(digits[i] < 9) {
digits[i] += 1;
return digits;
}
else {
digits[i] = 0;
}
}
if(digits[0] == 0) {
int [] temp = new int[digits.length + 1];
temp[0] = 1;
for(int i = 1; i < digits.length + 1; i++) {
temp[i] = digits[i - 1];
}
return temp;
}
return digits;
}
}