问题:给数组加一
具体为:给定的数字是用数组表示的,如[1,2,3]表示的数是123,所以123+1=124,再输出数组[1,2,4]
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.
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
思路:
最开始有想过先把数组转为数字,但是考虑到之前这么做过然后出现太长的数字时没法处理,所以直接在数组上进行的操作
最开始只在末尾+1,如果末尾为9,则末尾变为末尾-9,且指定进位标记flag=1,对数组从后到前进行进位,直到遇到不需要进位的时候为止
注意:需要考虑加一之后数字变多一位的可能,如999+1=1000,此时无法在原数组上进行修改,所以需要新建一个数组
class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
if(len==0){
return digits;
}
if(digits[len-1]+1<10) {
digits[len-1] ++;
return digits;
}
digits[len-1] = digits[len-1]-9;
int flag = 1;
for(int i=len-2;i>=0;i--){
if(digits[i] + flag <10){
digits[i] = digits[i] + flag;
flag = 0;
break;
}
if(digits[i] + flag+1>=10){
digits[i] = digits[i]-9;
}
}
if(flag==1){
digits = add1first(digits);
}
return digits;
}
// 新建一个数组,前面为1,后面为加1之后的结果
public static int[] add1first(int[] nums){
int len = nums.length;
int[] new_nums = new int[len+1];
new_nums[0] = 1;
for(int i=1;i<len+1;i++){
new_nums[i] = nums[i-1] ;
}
return new_nums;
}
}
结果:
Runtime: 0 ms, faster than 100.00%
Memory Usage: 37.3 MB, less than 19.04%