leetcode-Plus One 加一

本文详细解析了如何通过遍历数组的方式实现给定的非负整数加一的操作。主要讨论了三种可能的情况,特别是当数组末尾出现多个9的情况,并提供了具体的代码实现。

Plus One

question:

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

给定一个非负整数组成的非空数组,给整数加一。

可以假设整数不包含任何前导零,除了数字0本身。

最高位数字存放在列表的首位。
中文

 

分析:

分析会有三种可能,请看到下面的图

主要是判断9在那个位置

 代码实现:

class Solution {
    public int[] plusOne(int[] digits) {
        int length= digits.length;//数组长度
        for(int i = length-1;i>=0;i--){
            if(digits[i]!=9){// 判断9的位置
                digits[i]++;
                return digits;
            }
            digits[i]=0;
        }
        int[] newDigits= new int[length+1];//第三种可能
        newDigits[0]=1;
        return newDigits;
        
    }
}

 

视频链接: https://www.bilibili.com/video/av22183558/

 

转载于:https://www.cnblogs.com/liu-wang/p/8857893.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值