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

类似于大数相加的一个题

时间:2015-09-02 17:10:00      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer array of variable length like so [9, 8, 8, 3] where each item in array could be 0 to 9, write a function that would take would interpret the array [9, 8, 8, 3] as a number 9883 and increment it by 1. The return of the function would be an integer array containing the addition like so [9,8,8,4]. No zeros in the first position like [0,1,2,3]. I initially suggested a possible solution of process to convert the integer array to String then convert to Integer or Long and then do the addition of 1 and then convert it back to integer array. That is not allowed because the solution should be able to handle a very large number. Practice Tip: Remove the initial text, if any, in the G docs for more viewing room for code.

 

public static int[] bigAdd(int[] digits) {
    int currentDigitsSum = 1;
    for (int i=digits.length - 1; i > -1; i--) {
        currentDigitsSum = digits[i] + currentDigitsSum;
        digits[i] = currentDigitsSum % 10;
        if (currentDigitsSum /10 ==0) {
            return digits;
        } else {
            currentDigitsSum /= 10;
        }
    }
    if (currentDigitsSum != 0) {
        int[] newDigits = new int[digits.length + 1];
        System.arraycopy(digits, 0, newDigits, 1, digits.length);
        newDigits[0] = currentDigitsSum % 10;
        return newDigits;
    }
    return null;
}

 

类似于大数相加的一个题

标签:

原文地址:http://www.cnblogs.com/23lalala/p/4778888.html

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