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.
先来看几个例子:
998 + 1 = 999
979 + 1 = 980
999 + 1 = 1000
只有形如999这类的,+1 后数的位数才可能发生变化。
同时,以998 + 1为例,如果后面8 + 1没有发生进行,相当于前面的9 + 0,即不用再继续计算了。
运行时间:
代码:
public class PlusOne {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] != 9) {
digits[i]++;
break;//add 1 is done
} else {
digits[i] = 0; // need add 1 to the higher position
}
}
if (digits[0] == 0) {
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
return digits;
}
}