[leetcode]66Plus One

Posted stAr_1

tags:

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

/**
 * 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.
 */
/*
* 从最后一位到第二位倒着遍历,重写每位的数据,如果遇到不进位的情况,直接返回数据
* 由于第一位关系到是否需要新建数组,所以单独判断,只要运行完循环,肯定是有进位的,因为如果没有的话就返回了
* 所以不需要设置进位标志*/
public class Q66PlusOne {
    public int[] plusOne(int[] digits) {
        int l = digits.length;
        for (int i = l-1; i >=1 ; i--) {
            int cur = digits[i] + 1;
            digits[i] = cur % 10;
            if (cur / 10 == 0)
                return digits;
        }
        if (digits[0] < 9)
        {
            digits[0] += 1;
            return digits;
        }
        else
        {
            int[] res = new int[l+1];
            res[0] = 1;
            for (int i = l;i > 0;i-- )
            {
                res[i] = 0;
            }
            return res;
        }
    }
}

 

以上是关于[leetcode]66Plus One的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-66 Plus One

leetcode 66. Plus One

[LeetCode] 66. Plus One

[leetcode]66.Plus One

leetcode66 Plus One

[leetcode]66Plus One