《中英双解》leetCode Plus One (加一)

You are given a large integer represented as an integer array digits, where each digits[i] is the ith 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 leading 0'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;
   }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值