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

问题:

  问题很简单给出一个非负整数,用数组的方式表示改非负整数,例如321则给出一个三位数组[3][2][1],给该数组加一,返回结果数组。

分析:

  把两类特殊情况考虑上即可,如[1][9]、[9][9][9]。前者直接进一位,后者需要创建多一位的数组,保存结果。

public class Solution {
    public int[] plusOne(int[] digits) {
        int length = digits.length;
        int i=0;
        if(digits[length-1]!=9)                             最后一位不是9,直接加1
            digits[length-1]+=1;
        else{
            for(i=length-1;digits[i]==9;i--){         否则从最后一位向前循环找到第一位不是9的
                if(i==0){                    如果i==0了证明给出的数组都是9为第二种情况
                    int[] result = new int[length+1] ;
                    result[0]=1;
                    for(int j=1;j<=length;j++)
                        result[j]=0;
                    return result;
                }
                else{                      否则i!=0的话正常进位
                digits[i]=0;
            }
        }
        digits[i]+=1;
    }
    return digits;
}
}

 

posted @ 2014-10-26 10:32  buptzjf  阅读(189)  评论(0编辑  收藏  举报