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.

Java

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits.length < 1) {
            return digits;
        }

        int carry = 1;

        for(int i = digits.length - 1; i >= 0; i--) {
            int value = digits[i] + carry;
            carry = value / 10;
            digits[i] = value % 10; 
            if(carry == 0) {
                return digits;
            }
        }

        if(carry == 1) {
            int[] rst = new int[digits.length + 1];
            rst[0] = 1;
            return rst;
        } else {
            return digits;
        }
    }
}