题意:
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.
原题链接:https://leetcode.com/problems/plus-one/#/description
我知道你看不懂,给你翻译翻译:
就是给你一串非负非空整形数组,数组是由整数构成,每一位都存在数组里面,最高位存在最前面,例如 998,那这串数组就是{9,9,8},然后做加1操作,返回一串数组出来。还是{9,9,8},返回是{9,9,9},如果是{9,9},则返回的是{1,0,0}
思路:无非就是从数组尾加上来,在这个过程需要一个记录因子,记录是否需要进位加1,然后把值存在一个新数组,再最后for完之后看看这个记录因子是1还是0,定返回数组的长度,1把这个返回因子加上去,0不加,然后把新数组加上去。
完美。
No BB
Show Me Code!
代码:
public static int[] plusOne(int[] digits) {
int length = digits.length;
int[] newDigits = new int[length];
//記錄是否進位
int recordDigit = 1;
for(int i = length-1; i >= 0; i--){
if(digits[i] == 9 && recordDigit == 1){
newDigits[i] = 0;
recordDigit = 1;
} else {
newDigits[i] = digits[i] + recordDigit;
recordDigit = 0;
}
}
int[] resultDigits = new int[length + recordDigit];
if(recordDigit == 1){
resultDigits[0] = 1;
}
for(int i = recordDigit; i < length; i++){
resultDigits[i] = newDigits[i-recordDigit];
}
return resultDigits;
}
呵呵,解决!
之后有时间再看看有没有什么其他更快的解法。