2014年5月10日星期六

Loop Solution - Plus One - array add one

The idea is to loop the array. Be careful of the carry one (nextdigit). And the final next digit check!

A question needs to be clarified, 10 or bit or 16 or 8?

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits == null || digits.length == 0){
            return digits;
        }
        int nextDigit = 0;
        for(int i = digits.length - 1; i >=0; i--){
            if(digits[i] + nextDigit + ((i == digits.length - 1)?1:0)< 10){
                digits[i] = digits[i] + nextDigit + ((i == digits.length - 1)?1:0);
                nextDigit = 0;
            }else{
                digits[i] = digits[i] + 1 - 10;
                nextDigit = 1;
            }
        }
        if(nextDigit == 1){
            int[] result = new int[digits.length+1];
            result[0] = 1;
            for(int i = 0; i < digits.length; i++){
                result[i+1] = digits[i];
            }
            return result;
        }
        return digits;
    }
}

没有评论: