Tuesday, October 16, 2012

[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.

注意:数字不可以以0开头,所以我们要考虑最后进位的问题。如果超过原来的数组长度,得重新分配一个数组

Java code:


public int[] plusOne(int[] digits) {
        int add = 1;
        int len = digits.length;
        
        for(int i = len - 1; add > 0 && i >= 0; i--){
            digits[i] = (digits[i] + add)%10;
            add = (digits[i] + add)/10;
        }
        
        if( add > 0 ){
            
            int[] result = new int[len + 1];
            result[0] = add;
            
            for(int i = 1; i <= len; i++){
                result[i] = digits[i-1];
            }
            return result;
        }
       
        return digits;
    }

No comments:

Post a Comment