题目描述
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.
分析:整数型数组的最后一个元素加1,按照十进制操作,如果需要进位的话完成进位即可,并返回加1后的数组。
我的Code如下:
class Solution {
public int[] plusOne(int[] digits) {
//如果最后一位小于9,直接末位加1,并返回即可
if(digits[digits.length-1]<9){
digits[digits.length-1] = digits[digits.length-1] + 1;
return digits;
}
//数组array1用来倒序存储数组digits
int[] array1 = new int[digits.length + 1];
for(int i=0;i<digits.length; i++){
array1[i] = digits[digits.length - 1 - i];
}
//array首位加1,并进行进位操作
array1[0] = array1[0] + 1;
for(int i=0; i<digits.length; i++){
if(array1[i] > 9){
array1[i] = 0;
array1[i+1] = array1[i+1] + 1;
}
}
//array2倒序存储array1,此时已经得到正确结果,但是要判断应当输出的数组个数,因为array1,array2,array3的长度大于digits。
int[] array2 = new int[array1.length];
for(int i=0; i<array1.length; i++){
array2[i] = array1[array1.length - 1 -i];
}
if(array2[0] == 0){
for(int i=0; i<digits.length; i++){
array2[i] = array2[i+1];
}
int[] array3 = new int[digits.length];
for(int i=0; i<digits.length; i++){
array3[i] = array2[i];
}
return array3;
}else if(array2[0]>1){
int[] array3 = new int[digits.length];
for(int i=0; i<digits.length; i++){
array3[i] = array2[i];
}
return array3;
}else{
return array2;
}
}
}