其他分享
首页 > 其他分享> > 7. 加一

7. 加一

作者:互联网

加一

[原题链接](初级算法 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台 (leetcode-cn.com))

import java.util.Arrays;

public class Solution {
    /**
     * 时间复杂度O(n), 空间复杂度O(n/10)
     * 改为循环实现可节省递归产生的栈空间
     * @param digits
     * @return
     */
    public int[] plusOne(int[] digits) {
        if (plusOne(digits, digits.length - 1)){
            int[] newArray = Arrays.copyOf(digits, digits.length + 1);
            newArray[0] = 1;
            return newArray;
        }
        return digits;
    }

    /**
     * 数组元素从末尾开始递归+1(十进制进位)
     * 若数组长度不够,返回true
     * @param digits
     * @param i
     * @return
     */
    private boolean plusOne(int[]digits, int i){
        boolean carry;
        //边界判断
        if (i >= digits.length) return false;
        //当数组不够进位时,返回true,在调用该函数的函数中进行处理
        if (i < 0) return true;
        if (digits[i] < 9) {
            digits[i]++;
            return false;
        }
        digits[i] = 0;
        carry = plusOne(digits, i - 1);
        return carry;
    }
}

    可改写为循环,节省出递归栈空间

标签:digits,加一,return,int,param,数组,plusOne
来源: https://www.cnblogs.com/getheading/p/14878635.html