IncredibleThings

导航

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.

这道题考察数字进位,注意考虑溢出情况。

public class Solution {
    public int[] plusOne(int[] digits) {
        int len=digits.length;
        int pass=1;
        for (int i=len-1; i>=0; i--){
            if(digits[i]+pass >= 10){
                    
                    digits[i]=digits[i]+pass-10;
                    pass=1;
                if(i == 0){
                    int[] newDigits=new int[len+1];
                    for(int j=len; j>0; j--){
                        newDigits[j]=digits[j-1];
                    }
                    newDigits[0]=pass;
                    return newDigits;
                    
                }
                    
            }
            else{
                digits[i]=digits[i]+pass;
                pass=0;
            }
        }
        return digits;
    }
}

  

posted on 2016-05-04 04:20  IncredibleThings  阅读(124)  评论(0编辑  收藏  举报