问题描述:
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
思路:
情况1:每一位都是9, 这样我们需要一个更大的数组,返回类似这样的结果[1,0,0,0…0]
情况2: 并非每一位都是9,返回结果的数组与给定数组大小一样。我们用另一个数组carryover记录进位‘1’, 然后根据具体情况判断是否需要进位。
代码:
class Solution {
public int[] plusOne(int[] digits) {
int i=0;
int counter=0;
for (; i<digits.length;i++){
if (digits[i]==9){
counter++;
}
}
if (counter==digits.length){//case 1: if all digits are 9, need an array of bigger size
int[] result = new int[digits.length+1];
result[0]=1;
for (int j=1; j<result.length; j++){
result[j]=0;
}
return result;
}
else{//case 2: no need to make the array bigger
int[] carryover = new int[digits.length];
int[] result = new int[digits.length];
carryover[digits.length-1]=1;
for (int j=digits.length-1; j>=0; j--){
if (digits[j]+carryover[j]==10){
result[j]=0;
carryover[j-1]=1;
}
else{
result[j]=digits[j]+carryover[j];
}
}
return result;
}
}
}
时间复杂度: O(n)