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.

leetcode-Plus One 加一leetcode-Plus One 加一
给定一个非负整数组成的非空数组,给整数加一。

可以假设整数不包含任何前导零,除了数字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/

 

相关文章:

  • 2021-12-03
  • 2021-07-03
  • 2021-09-20
  • 2022-01-27
  • 2022-01-29
  • 2022-01-13
猜你喜欢
  • 2021-11-08
  • 2021-05-17
  • 2021-09-10
  • 2022-01-20
  • 2022-12-23
  • 2021-09-26
  • 2021-08-20
相关资源
相似解决方案