66. Plus One

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.

这道题我一开始的想法是将数组中的数字转化为int型的数,对其加一后重新化成int数组即可,但是我没有想到一个问题就是int能表示的范围,当例子中给出大数的时候int型表示不出来了,我就想到了用double来表示,但是依旧还会存在很多问题,于是我放弃了这一个想法。

我看了一下LeetCode上网友的做法,其中有一种做法很巧妙

class Solution {
    public int[] plusOne(int[] digits) {
        int len=digits.length;
        for(int i=len-1;i>=0;i--)
        {
            if(digits[i]<9)
            {
                digits[i]++;
                return digits;
            }
            else
                digits[i]=0;
        }
        int []newdig=new int[len+1];
        newdig[0]=1;
        return newdig;
    }
}

从末尾开始,如果数字小于9就直接++即可,如果等于9就把该位变成0,对前位++。if循环中的return语句保证了+1后循环的结束,这里十分的巧妙,而且这一做法导致for循环结束后就只有全为9的情况,只要对这种情况作处理即可,很厉害。

这里也提醒一下自己要去看一下对于大数的处理,我觉得很有必要。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值