Leet Code OJ 66. Plus One [Difficulty: Easy]

Posted Lnho

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet Code OJ 66. Plus One [Difficulty: Easy]相关的知识,希望对你有一定的参考价值。

题目:
Given a non-negative number represented as an array of digits, plus one to the number.

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

翻译:
给定一个非负数,它是有数字的数组组成,把这个非负数+1。
这个非负数的存储方式,是把最高有效位数字放到列表的前面。

分析:
首先考虑的是进位,当最后一位是“9”的时候,会发生向前进位。
再考虑一种特殊情况”999”,执行加一操作后,数组的长度变了,这个时候需要重新创建一个新数组。笔者采用一个标志位needAdd,用来记录循环完成时,是否还有未进的位。

代码:

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits.length==0){
            return new int[]{1};
        }
        int index=digits.length-1;
        boolean needAdd=false;
        while(index>=0){
            digits[index]++;
            if(digits[index]<10){
                needAdd=false;
                break;
            }
            digits[index]-=10;
            index--;
            needAdd=true;
        }
        if(needAdd){
            int[] digitsNew=new int[digits.length+1];
            for(int i=0;i<digits.length;i++){
                digitsNew[i+1]=digits[i];
            }
            digitsNew[0]=1;
            return digitsNew;
        }
        return digits;
    }
}

以上是关于Leet Code OJ 66. Plus One [Difficulty: Easy]的主要内容,如果未能解决你的问题,请参考以下文章

Leet Code OJ 223. Rectangle Area [Difficulty: Easy]

Leet Code OJ 338. Counting Bits [Difficulty: Easy]

Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]

Leet Code OJ 27. Remove Element [Difficulty: Easy]

Leet Code OJ 189. Rotate Array [Difficulty: Easy]

Leet Code OJ 338. Counting Bits [Difficulty: Medium]