LeetCode 66. Plus One

Problem:

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.

Solution:

only need a carry variable

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = (digits[digits.length - 1] + 1) / 10;
        digits[digits.length - 1] = (digits[digits.length - 1] + 1) % 10;
        for (int i = digits.length - 2; i >= 0; i--) {
            int temp = digits[i];
            digits[i] = (carry + digits[i]) % 10;      
            carry = (carry + temp) / 10;
        }
        if (carry == 0) return digits;
        int[] result = new int[digits.length + 1];
        System.arraycopy(digits, 0, result, 1, digits.length);
        result[0] = 1;
        return result;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *