leetcode-Plus One 加一

leetcode-Plus One 加一

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在那个位置

leetcode-Plus One 加一

 代码实现:

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/