题目地址:
https://www.lintcode.com/problem/plus-one/description
给定一个数组,代表一个十进制正整数的各个位(从左到右从高位到低位)。返回代表此数加 1 1 1后的数对应的数组。代码如下:
public class Solution {
/**
* @param digits: a number represented as an array of digits
* @return: the result
*/
public int[] plusOne(int[] digits) {
// write your code here
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
digits[i] += carry;
carry = digits[i] / 10;
digits[i] %= 10;
}
// 需要讨论最高位有无进位
if (carry == 0) {
return digits;
}
int[] res = new int[digits.length + 1];
res[0] = 1;
for (int i = 0; i < digits.length; i++) {
res[i + 1] = digits[i];
}
return res;
}
}
时空复杂度 O ( n ) O(n) O(n)(如果最高位有进位则需要新开一个数组,否则直接在原数组上操作返回即可)。