lintcode-easy-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.

Given [1,2,3] which represents 123, return [1,2,4].

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

public class Solution {
    /**
     * @param digits a number represented as an array of digits
     * @return the result
     */
    public int[] plusOne(int[] digits) {
        // Write your code here
        if(digits == null || digits.length == 0){
            int[] result = new int[1];
            result[0] = 1;
            return result;
        }
        
        int carry = 1;
        for(int i = digits.length - 1; i >= 0; i--){
            int temp = carry;
            carry = (digits[i] + carry) / 10;
            digits[i] = (digits[i] + temp) % 10;
        }
        
        if(carry == 0)
            return digits;
        else{
            int[] result = new int[digits.length + 1];
            result[0] = 1;
            for(int i = 1; i < result.length; i++)
                result[i] = digits[i - 1];
            return result;
        }
    }
}

 

你可能感兴趣的:(lintcode-easy-Plus One)