[LeetCode]66. 加一(Plus One)Java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40914991/article/details/82055109

一、题目:

LeetCode地址

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

最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。

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

示例 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。

示例 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

二、分析:

该题用了递归,处理之后,若最高位为10,数组0索引为1,其他为0。

三、Java代码:

public static int[] plusOne(int[] a) {
        a[a.length-1]++;
        a = plus(a,a.length-1);
        if(a[0]==10){
            int[] b = new int[a.length+1];
            b[0]=1;
            return b;
        }
        return a;
    }
    private static int[] plus(int[] a,int i){
        if(i==0){
            return a;
        }
        if (a[i]==10) {
            a[i] = 0;
            a[i-1]++;
            plus(a,i-1);
        }
        return a;
    }

四、提交结果:

猜你喜欢

转载自blog.csdn.net/qq_40914991/article/details/82055109