[leetcode] Plus One

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

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

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

思路:大数计算的思想,注意carry的处理。如果最高位进位需要重新分配数组空间。

import java.util.Arrays;

public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0)
            return digits;
        int n = digits.length;
        int i;
        int c = 1;
        for (i = n - 1; i >= 0; i--) {
            if (c == 0)
                break;
            digits[i] += c;
            if (digits[i] > 9) {
                digits[i] -= 10;
                c = 1;
            } else
                c = 0;

        }
        if (c == 1) {
            int[] newDigits = new int[n + 1];
            newDigits[0] = 1;

            for (i = 0; i < n; i++)
                newDigits[i + 1] = digits[i];

            return newDigits;
        } else
            return digits;

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution().plusOne(new int[] { 1, 9, 9 })));

    }

}
View Code
原文地址:https://www.cnblogs.com/jdflyfly/p/3812487.html