LintCode-407.加一

题目

描述

给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。
该数字按照大小进行排列,最大的数在列表的最前面。

样例

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

给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

解答

思路

由于是加一,就简单多了。从后往前

  1. 只要是某一位加1之后小于10。直接返回。
  2. 加到最后一位都没有返回,说明要进1,而new出来的int[]默认设置为0,只需要把首位设为1就行了。

代码

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
        for(int i = digits.length - 1;i >= 0 ;i--){
            if(++digits[i]>9) digits[i] = 0;
            else return digits;
        }
        int[] temp = new int[digits.length + 1];temp[0]=1;
        for(int i = 1; i < temp.length;temp[i++]=0);
        return temp;
    }
}

你可能感兴趣的:(LintCode-407.加一)