码迷,mamicode.com
首页 > 其他好文 > 详细

plus one

时间:2015-06-24 22:21:56      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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

 

plus one

标签:

原文地址:http://www.cnblogs.com/hf-cherish/p/4598695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!