首页 > 其他 > 详细

类似于大数相加的一个题

时间:2015-09-02 17:09:28      阅读:219      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!