lintcode 加一(Plus One )(Java)

来源:互联网 发布:类似origin的软件 编辑:程序博客网 时间:2024/04/30 15:16

1.题目详情

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,返回一个新的数组。
该数字按照大小进行排列,最大的数在列表的最前面。

2.样例

给定 [1,2,3] 表示 123, 返回 [1,2,4].
给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

3.分析
本来的思路是转化为string->int->int[],这个念头一闪而过我就感觉不对了,可能是潜意识里每次碰到处理数字的都想转string处理,后来做的题多了发现这种想法一般都是错的。

正确思路分析:如果数组的最后一位不是9的话,那么直接最后一位自身增加1返回数组即可;如果碰到是9的情况,则需要考虑进位的情况,从后往前遍历循环,如果为为9则赋值为0,前一位加1,如果不为9则加一返回,或者循环结束,如果循环结束还没有return,则可以判断每位都是9,则可以全赋值为0,前面增加一个1。

4.代码

public class Solution {    /**     * @param digits a number represented as an array of digits     * @return the result     */    public int[] plusOne(int[] digits) {        // Write your code here        int n = digits.length;        for (int i = n - 1; i >= 0; i--){            if (digits[i] == 9){                digits[i] = 0;            }else {                digits[i]++;                return digits;            }        }        //创建一个新数组,长度加1         int[] result = new int[n + 1];         result[0] = 1;         return result;    }}