zoukankan      html  css  js  c++  java
  • 类似于大数相加的一个题

    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;
    }
  • 相关阅读:
    二维数组的查找问题
    将字符串编码成数值,求数值最大和问题(今日头条笔试题)
    链表的倒序打印
    求方程的近似解
    多边形构成问题(今日头条笔试题)
    各种语言数据类型大小
    luoguP1551 亲戚
    Codeforces 764 A-B
    Mixing Chemicals
    Day 8 of JZJX
  • 原文地址:https://www.cnblogs.com/23lalala/p/4778888.html
Copyright © 2011-2022 走看看