Plus One

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

    Example

    Given [9,9,9] which represents 999, return [1,0,0,0].

    1. /**
    2. * @return the result
    3. */
    4. public int[] plusOne(int[] digits) {
    5. return plusDigit(digits, 1);
    6. }
    7. private int[] plusDigit(int[] digits, int digit) {
    8. // regard digit(0~9) as carry
    9. int carry = digit;
    10. int[] result = new int[digits.length];
    11. for (int i = digits.length - 1; i >= 0; i--) {
    12. carry = (digits[i] + carry) / 10;
    13. }
    14. if (carry == 1) {
    15. int[] finalResult = new int[result.length + 1];
    16. finalResult[0] = 1;
    17. return finalResult;
    18. }
    19. return result;
    20. }
    21. }

    源码中单独实现了加任何数(0~9)的私有方法,更为通用,对于末尾第一个数,可以将要加的数当做进位处理,这样就不必单独区分最后一位了,十分优雅!