[LeetCode]66. Plus One

本文解析了一道关于数组表示的十进制数加一的算法题。通过三种情况的讨论,给出了具体的实现思路及Java代码示例。适用于初学者理解和掌握数组与数值操作的基本方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

66. Plus One

一、题目

Problem Description:
Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3:
Input: digits = [0]
Output: [1]

Constraints:
1 < = d i g i t s . l e n g t h < = 100 1 <= digits.length <= 100 1<=digits.length<=100
0 < = d i g i t s [ i ] < = 9 0 <= digits[i] <= 9 0<=digits[i]<=9

二、题解

  • 给出一个数组,代表一个十进制数,数组索引为0的元素表示此十进制数的最高位。对此十进制数加一,返回一个仍用数组表示的十进制数
  • 一道简单题,可分为以下几种情况:
    ①最末位不为9,最末尾直接加一
    123 + 1 = 124
    ②从末位起,连续n位为9,其中 n < 数组长度
    699 + 1 = 700
    ③给定数各位都为9,最后输出一个首元素为1,其余元素为0,长度增加一位的数组
    999 + 1 = 1000
    根据以上情况讨论,可直接编写以下代码。
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[] res = new int[len + 1];
        res[0] = 1;
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值