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.
//思想類似於前兩天的add binary與add two numbers
//數組中,高位在左,低位在右,故反向遍歷並維護進位
public class Solution {
public int[] plusOne(int[] digits) {
if(digits==null || digits.length==0){
return null;
}
int carry = 1; //在第一次循環時,充當one的角色,以後作爲進位標誌位
int index = digits.length - 1;
while(index >= 0){
int temp = digits[index] + carry;
int newDigit = temp % 10;
carry = temp / 10;
digits[index] = newDigit;
index--;
}
if(carry > 0){ //因僅僅加1,若此時還有進位,則原數組畢爲9999..形式
int[] result = new int[digits.length+1];
result[0] = 1; //新建個擴充數組,且首位爲1即可
return result;
}else{
return digits;
}
}
}