一 题目
Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
二 分析
easy 级别,给个数组,加1返回。主要是数组考虑进位的情况。
一开始为了省事,我就用转换为数字,加1后再返回。
public static int[] plusOne(int[] digits) {
long tmp =0;
for(int i=digits.length-1;i>=0;i--){
tmp +=Math.pow(10, digits.length-1-i) *digits[i];
}
tmp = tmp+1;
int length = digits.length;
//输出
if((tmp+"").length()> digits.length){
length = length+1;
}
//格式化
int[] res = new int[length];
for(int j=length-1;j>=0;j-- ){
res[j]= (int) (tmp%10);
tmp =tmp/10;
}
return res;
}
但是提测不过。遇到这种{6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3} 超过范围就不行了。所以还得老实回去。
<9 则加1后直接返回,否则置0后继续迭代,如果中间没有返回,则全部为9.考虑进位情况。
public static int[] plusOne(int[] digits) {
for(int i=digits.length-1;i>=0;i--){
int tmp = digits[i];
if(tmp<9){
digits[i] = tmp+1;
return digits;
}else{
digits[i]=0;
}
}//考虑全部是9,进位的情况
int[] res = new int[digits.length+1];
res[0]=1;
return res;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.
Memory Usage: 35.2 MB, less than 97.58% of Java online submissions for Plus One.
时间复杂度O(N)