Wednesday, July 16, 2014

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.

只需要在最后确认下carry是否为1。
public class Solution {
    //Time: O(n)
    public int[] plusOne(int[] digits) {
        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            int cur = digits[i] + carry;
            digits[i] = cur % 10;
            carry = cur / 10;
        }
        if (carry == 1) {
            int[] res = new int[digits.length + 1];
            for (int i = 1; i < res.length; i++) {
                res[i] = digits[i - 1];
            }
            res[0] = 1;
            return res;
        }
        return digits;
    }
}

No comments:

Post a Comment