leetcode-66-加一

问题:

 

package com.example.demo;

public class Test66 {

    /**
     * 加一:
     * 从后向前遍历,分当前位置是否为9,9时,会进一
     */
    public int[] plusOne(int[] digits) {
        for (int i = digits.length - 1; i >= 0; i--) {
            digits[i]++;
            digits[i] %= 10;
            if (digits[i] != 0) {
                return digits;
            }
        }
        // 如果上边钱都处理完,走到该位置时,代表原来的数组为:999格式,
        // 这种情况下,则需要进行重建数组,索引0处为1,其余为0
        int[] res = new int[digits.length + 1];
        res[0] = 1;
        return res;
    }

    public static void main(String[] args) {
        Test66 t = new Test66();
        int[] arr = {0};
        int[] ints = t.plusOne(arr);
        for (int anInt : ints) {
            System.out.print(anInt);
        }
    }
}

 

posted @ 2019-08-02 23:24  xj-record  阅读(123)  评论(0编辑  收藏  举报