題目描述
給定一個由整數組成的非空數組所表示的非負整數,在該數的基礎上加一,最高位數字存放在數組的首位, 數組中每個元素只存儲單個數字,你可以假設除了整數 0 之外,這個整數不會以零開頭。
示例
輸入: [1,2,3]
輸出: [1,2,4]
解釋: 輸入數組表示數字 123。
輸入: [4,3,2,1]
輸出: [4,3,2,2]
解釋: 輸入數組表示數字 4321。
解題思路
class Solution {
public int[] plusOne(int[] digits) {
//獲取個位數,即數組最後一個元素
int length=digits.length;
int lastIndex=length-1;
//加1
digits[lastIndex]+=1;
//判斷最後一個元素是否大於9
if(digits[lastIndex]>9){
while(lastIndex>0 && digits[lastIndex]>9){
digits[lastIndex]=0;
digits[lastIndex-1] += 1;
lastIndex--;
}
//判斷是否只有個位數
if(lastIndex==0 && digits[lastIndex]>9){
//數組擴容
digits=new int[length+1];
digits[0]=1;
}
}
return digits;
}
}