0
点赞
收藏
分享

微信扫一扫

Day36 加一

给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一

https://leetcode-cn.com/problems/plus-one/

数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

示例1:

示例2:

示例3:

提示:

Java解法

package sj.shimmer.algorithm.m2;

import sj.shimmer.algorithm.Utils;

/**
 * Created by SJ on 2021/3/1.
 */

class D36 {
    public static void main(String[] args) {
        Utils.logArray(plusOne(new int[]{1, 2, 3, 4, 5, 6}));
        Utils.logArray(plusOne(new int[]{9,9,9}));
    }

    public static int[] plusOne(int[] digits) {
        if (digits != null && digits.length > 0) {
            int length = digits.length;
            int sum = digits[length - 1] + 1;
            digits[length - 1] = sum % 10;
            int temp = sum / 10;
            int i = length - 2;
            while (i >= 0 && temp > 0) {
                sum = digits[i] + temp;
                digits[i] = sum % 10;
                temp = sum / 10;
                i--;
            }
            if (temp>0) {
                int[] result = new int[length+1];
                result[0] = temp;
                for (int j = 1; j < result.length; j++) {
                    result[j] = digits[j-1];
                }
                return result;
            }
        }
        return digits;
    }
}

参考解

https://leetcode-cn.com/problems/plus-one/solution/java-shu-xue-jie-ti-by-yhhzw/

举报

相关推荐

0 条评论