leetcode - 66.Plus One

    xiaoxiao2021-03-25  63

    Plus One

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    Solution1:

    public int[] plusOne(int[] digits) { return plus(digits, digits.length - 1, 1); } private int[] plus(int[] digits, int end, int i) { if (i == 0) { return digits; } if (end == -1) { int[] _digits = new int[digits.length + 1]; System.arraycopy(digits, 0, _digits, 1, digits.length); _digits[0] = i; return _digits; } int num = digits[end] + i; digits[end] = num % 10; return plus(digits, --end, num / 10); }

    Solution2:

    public int[] plusOne(int[] digits) { int n = digits.length; for (int i = n - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] newNumber = new int[n + 1]; newNumber[0] = 1; return newNumber; }
    转载请注明原文地址: https://ju.6miu.com/read-40779.html

    最新回复(0)