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.

 

将一个整型数组当成一个整数,将该数加一后返回所得新的数组。

所要考虑的是进位和溢出问题,和Add Binary这道题类似,从低位逐位和进位相加,直至不产生进位为止,假若最高位产生进位,则组要new一个新的数组,size+1,并将新数组第一位置1,后面接上刚刚加完1的数组。

完整代码:

public class Solution {
    public int[] plusOne(int[] digits) {
        int size = digits.length;
        int carry = 1;
        for(int i=size-1;i>=0;i--){
            int sum = digits[i]+carry;
            if(sum>=10){
                carry = 1;
                digits[i] = sum-10;
            }
            else{
                carry = 0;
                digits[i] = sum;
                break;
            }
        }
        if(carry==1){
            int[] re = new int[size+1];
            re[0] = 1;
            for(int j = 0;j<size;j++){
                re[j+1] = digits[j];
            }
            return re;
        }
        return digits;
    }
}

 

posted @ 2015-02-04 20:59  mrpod2g  阅读(156)  评论(0编辑  收藏  举报