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.
ExampleGiven [1,2,3]
which represents 123, return [1,2,4]
.
Given [9,9,9]
which represents 999, return [1,0,0,0]
比較簡(jiǎn)單的題,從尾到頭遍歷崩掘,然后如果有進(jìn)位依次加一七嫌,最后在判斷是否需要加一個(gè)數(shù)字到數(shù)組頭。
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
if(digits == null || digits.length < 1){
return digits;
}
int adder = 1;
for (int i = digits.length-1; i >= 0 && adder > 0; i--) {
int sum = digits[i] + adder;
digits[i] = sum % 10;
adder = sum / 10;
}
if(adder == 0){
return digits;
}
int[] num = new int[digits.length + 1];
num[0] = 1;
for( int j = 1; j < digits.length; j++) {
num[j] = digits[j-1];
}
return num;
}
}