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.
这道题晃眼看上去很简单,其实不然,考察的知识点还是挺多的,一般的思路会考虑新建一个数组,把+1后的数一位一位存到新的数组中去,这样做的坏处就是每次都一定会新建数组。而理想的情况应该是不用新建数组,直接在原数组上改,只有遇到99,999,9999这样的数才需要新建数组。
代码如下
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0)
return digits;
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
carry = digits[i] + carry;
digits[i] = carry % 10;
carry = carry / 10;
if (carry == 0)
return digits;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}