Given a non-negative integer represented as a non-empty array 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.
用一個數(shù)組代表一個數(shù)字,求+1以后的值,數(shù)組返回形式。
加1以后兩種情況:1、產(chǎn)生進(jìn)位,高一位的數(shù)繼續(xù)加1;2、沒有進(jìn)位,高位的數(shù)保持原樣。
注意:99或999這樣各位都是9的數(shù),最后的結(jié)果會比原來的數(shù)多一位。
自己的思路是用out作為進(jìn)位標(biāo)志,如果一個循環(huán)結(jié)束,out還表示有進(jìn)位,證明是99這樣的情況,需要再增加一位。
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0) {
int[] res = new int[1];
res[0] = 1;
return res;
}
List<Integer> list = new LinkedList<>();
boolean out = true;
for (int i = digits.length - 1; i >= 0; i--) {
if (out) {
if (digits[i] == 9) {
list.add(0, 0);
} else {
list.add(0, digits[i] + 1);
out = false;
}
} else {
list.add(0, digits[i]);
}
}
if (out) {
list.add(0, 1);
}
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
return res;
}
自己用了一個list,所以空間復(fù)雜度是O(n)。翻看discuss,了解到自己處理的有些多余了,因?yàn)閮H僅是99這樣的情況會多一位,其他時(shí)候如果不產(chǎn)生進(jìn)位,則直接修改傳入的原數(shù)組再返回就可以了。
public int[] plusOne1(int[] digits) {
if (digits == null || digits.length == 0) {
return new int[]{1};
}
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
} else {
digits[i] = 0;
}
}
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}