You are given a large integer represented as an integer array
digits
, where eachdigits[i]
is theith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading0
's.Increment the large integer by one and return the resulting array of digits.
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
Example 1:
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].Example 2:
Input: digits = [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus, the result should be [4,3,2,2].Example 3:
Input: digits = [0] Output: [1] Explanation: The array represents the integer 0. Incrementing by one gives 0 + 1 = 1. Thus, the result should be [1].Example 4:
Input: digits = [9] Output: [1,0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be [1,0].
一些生词:
to least:至少
Increment
英 [ˈɪŋkrəmənt] 美 [ˈɪŋkrəmənt]
增量;递增;自增;增加;增量方式
这也是一个简单题,先说一下我的思路,我们的目的是要求将数组的最后一个元素加以,此时就会出现一个问题,那就是个位超过十之后,那么前面几位如何自增呢?现在来看看代码。
class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
for(int i = length - 1;i >= 0;i--){
digits[i] = (digits[i] + 1) % 10;//取余是因为防止数大于10
if(digits[i] != 0) return digits;
//此时如果等于0,那么会自动再次进入循环,i--
}
//解决数组长度为1的问题
digits = new int[length + 1];//为什么要length+1呢?大家可以想一下,如果数组长度为1
//那么数组只能存储一个数
digit[0] = 1;//这个方法有点取巧了
return digits;
}
}