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;
    }
  • 相关阅读:
    Flexigrid 完成表格数据显示
    地图高度自适应
    Vmware汉化版下载
    EasyUI grid 封装JSON数据
    C# 中的委托和事件
    C#中的委托和事件(续)
    从dataReader到Entity转化时利用Reflect示例
    sql 压缩数据库出错
    输入日期可以计算星期几
    用CSS调整scrollbar(滚动条)的配色
  • 原文地址:https://www.cnblogs.com/23lalala/p/4778888.html
Copyright © 2011-2022 走看看