首页 文章

整数迭代帮助java

提问于
浏览
1

我目前有一个关于将整数数组合成一个整数的问题 .

我在Way to combine integer array to a single integer variable?调查了其他几种方法,但我仍然不明白为什么我会遇到错误 .

我的目标是转向:

[6, 2, 3, 3, 8, 7, 7, 7, 0, 1, 6]

62338777016

当给定较小的整数数组时,它目前有效,例如:

[1, 3, 4, 4]
-> 1344

一旦元素数量达到10,它就会开始崩溃 . 有没有人有可能的解决方案?

6 回答

  • 0

    您正在溢出整数的最大大小2147483647.解决此问题的一种方法是使用BigInteger而不是 int

    BigInteger bigInt = BigInteger.ZERO;
    for (int i : ints) {
        bigInt = bigInt.multiply(BigInteger.TEN).add(BigInteger.valueOf(i));
    }
    
  • 0

    在这里,您尝试使用超过10位数的整数,超过最大值2,147,483,647,因此您可以使用下面的代码进行微小的更改,例如使用double .

    Integer[] arr = new Integer[] { 6, 2, 3, 3, 8, 7, 7, 7, 0, 1, 6 };
        Double myData = 0d;
        for (int i = 0; i < arr.length; i++) {
            double productfactor = (Math.pow(10, (arr.length-1-i)));
            myData = myData+arr[i]*productfactor;
        }
        String formatted = new BigDecimal(Double.valueOf(myData)).toString();
    
  • -1

    你可以像这样执行:

    Integer[] arr = {6, 2, 3, 3, 8, 7, 7, 7, 0, 1, 6};
    Long val = Long.valueOf(Arrays.stream(arr).map(String::valueOf).collect(Collectors.joining("")));
    
  • 0
    public static long convert(int[] arr) {
        long res = 0;
    
        for (int digit : arr) {
            // negative value is marker of long overflow
            if (digit < 0 || res * 10 + digit < 0)
                throw new NumberFormatException();
            res = res * 10 + digit;
        }
    
        return res;
    }
    

    这不是一种通用的方法,因为 Long.MAX_VALUE . 另外,你必须使用 BigInteger 而不是长 .

    public static BigInteger convert(int[] arr) {
        // reserve required space for internal array
        StringBuilder buf = new StringBuilder(arr.length);
    
        for (int digit : arr)
            buf.append(digit);
    
        // create it only once
        return new BigInteger(buf.toString());
    }
    
  • 0

    我们需要确定错误消息,但我的第一个猜测是你达到int的大小限制(2,147,483,647) .

  • 0

    那么解决这个问题的一种可能方法是,我假设所有整数都是正数 .

    您可以将所有整数数组值连接成一个String并形成一个字符串 .

    所以, [6, 2, 3, 3, 8, 7, 7, 7, 0, 1, 6] 变为 62338777016 (String) .

    BigInteger有一个构造函数(https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String)

    您可以利用它来获取值的BigInteger表示 .

相关问题