HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. Question

给定一个非负数,用数组存储其各数位,对这个数加一,返回结果。数组中,最高位在数组头。

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.
View Code

2. Solution

public class Solution {
    public int[] plusOne( int[] digits ){
        digits[digits.length-1]++;
        int i;
        for( i=digits.length-1; i>0 && digits[i]/10 != 0; i-- ){
            digits[i-1] += digits[i]/10;
            digits[i] = digits[i] % 10;
        }
        int[] res = null;
        int k;    //the start point of res to copy from digits
        if( digits[i]/10!=0 ){
            res = new int[ digits.length + 1 ];
            res[0] = digits[i] / 10;
            digits[i] = digits[i] % 10;
            k = 1;
        }
        else{
            res = new int[ digits.length ];
            k = 0;
        }
        System.arraycopy(digits, 0, res, k, digits.length);
        return res;
    }
}
View Code

 

posted on 2015-06-24 21:26  HF_Cherish  阅读(178)  评论(0编辑  收藏  举报