【问题标题】:How to convert int array into int如何将int数组转换为int
【发布时间】:2019-05-04 15:54:12
【问题描述】:

目前我开始阅读一本关于 alogirthms 的书,所以我现在正在尝试一些非常简单的算法来适应转换等等。在这个小班上,我想启用一个带有进位的学校添加功能。

如何将生成的 Int 数组转换为 int?我不知道如何将它们转换为足够的..

当前结果是 [7, 8, 3, 7, 9, 0, 5, 6],我想将这些数字连接成 (78379056) 的一个整数。我有哪些可能性?

public class Addition {

    public int[] addiere(int[] a, int[] b) {
        int res = 0;
        int[] c = new int[a.length];
        for(int i = a.length-1 ; i>=0 ; i--) {
            res = a[i]+b[i];
            if(res>=10) {
                c[i] = oneValue(res);
                a[i-1]+=1;
            } else c[i]=res;
            System.out.println("a -- "+a[i]+"  b -- "+b[i]+"  c -- "+c[i]);
        }
        return c;
    }

    public int oneValue(int t) {
        String res;
        int val;
        res=Integer.toString(t);

        res = res.substring(res.length()-1);
        val = Integer.parseInt(res);

        return val;

    }


    public static void main(String[] args) {

        int[] a = {3,4,6,8,9,1,2,4};
        int[] b = {4,2,5,7,8,9,3,2};

        Addition add = new Addition();
        int[] result;

        //returns an array of Integers
        System.out.println(Arrays.toString(add.addiere(a, b)));

        result = add.addiere(a, b);

        //HERE should be a method to convert the result ( Array of Integers ) just into a normal integer
    }

}

【问题讨论】:

  • 请在您的问题中添加完整的问题陈述。这种方法应该做什么?样本输入输出是什么?
  • 两个数组的长度是否相同?如果输入是{9}, {9},会发生什么?数组可以有2位数字还是3位数字?
  • @SMA 我首先只是寻找基本情况,其中解析的数字是从 0 到 9 的整数。扩展可能会在以后出现。但我期待的是{9}, {9} 案例。您有什么改进建议吗?

标签: java arrays int


【解决方案1】:

给定数组

int arr[] = { 7, 8, 3, 7, 9, 0, 5, 6 };

你可以这样做:

long num = Long.parseLong(Arrays.stream(arr)
                                .mapToObj(String::valueOf)
                                .collect(Collectors.joining()));

哪个输出

78379056


解释:

  1. mapToObj(...) 中,我们将每个元素从int 转换为 使用valueOf 方法的String
  2. 接下来,我们将这些单独的字符串中的每一个收集到一个字符串中 Collectors.joining() 的意思
  3. 现在,我们将 this 字符串转换为长字符串。你可以阅读更多关于 来自文档here 的流

我们在这里使用 long 以防万一数字太大而无法包含在 int 中

【讨论】:

  • 这真是一个使用流的好案例!您能详细介绍一下.mapToObject() 函数的工作原理吗?也许你可以说一下签名IntFunction<? extends U> mapper我不太明白那里发生了什么..
  • 当然。在mapToObj(...) 中,我们使用valueOf 方法将each 元素从int 转换为String。接下来,我们通过Collectors.joining(...) 将这些单独的字符串中的每一个收集到one 字符串中。现在,我们将此字符串转换为long。您可以从文档here 中阅读有关流的更多信息。编辑答案以反映相同。
  • 太棒了!非常感谢!剩下一个问题 - 你能告诉我如何阅读 .mapToObj()-function 的引用签名吗? IntFunction 是什么?这是否意味着函数必须返回 IntValue 或如何定义 IntFunction? U 是什么? 映射器是什么?
  • 通过 cmets 很难解释这些概念。 1、IntFunction是一个功能接口。 2.U用于表示使用泛型。 3.mapper泛型U的引用名。我建议您尝试阅读更多这些主题以更好地理解。
  • @Twixx:如果这个答案有帮助,请考虑接受/支持它。What should I do when someone answers my question?
【解决方案2】:

您可以将数组转换为字符串并使用 Integer.parseInt() 来获得此结果,或者使用简单的循环将数字乘以 10 与它们的位置指数相加:

int r = 0;
for (int i = 0; i < result.length; i++) {
    r += result[i] * Math.pow(10, result.length - i - 1);
}

我更喜欢这个解决方案。

数组[7, 8, 3, 7, 9, 0, 5, 6] 的结果是78379056

此外,如果您的数字超出 int 范围 (78379056),您应该考虑使用 long 而不是 int

编辑:这是Integer.parseInt()的解决方案:

StringBuilder builder = new StringBuilder();
for (int i : result) {
    builder.append(i);
}
int r = Integer.parseInt(builder.toString());

您也可以看看 Nicholas K 的回答。

【讨论】:

  • 我想使用Integer.parseInt()选项,但问题是,如果我要执行System.out.println(Integer.parseInt(result.toString()));,控制台会打印出:Exception in thread "main" java.lang.NumberFormatException: For input string: "[I@7852e922" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at dAbgabe.Addition.main(Addition.java:47)
  • @Twixx 你不能使用Array.toString() 你必须自己生成字符串。我将其添加到我的答案中。或者看看他使用的 Nicholas K 的答案是使用流和长结果。
【解决方案3】:
    public static void main(String[] args) {
        int[] a =  {7, 8, 3, 7, 9, 0, 5, 6};


        int m = 1;
        int r = 0;

        for (int i=a.length-1; i>=0; i--) {
            r = a[i] * m + r;
            m = m * 10;
        }

        System.out.println(r);
    }

打印:

78379056

【讨论】:

    【解决方案4】:

    最终,您可以将每个数字乘以 10 的幂,然后将它们相加。例如此代码将返回“1234”。

    int[] array = {1, 2, 3, 4};
    int total = 0;
    for(int i = 0; i < array.length; i++)
        if(array[i] > 9 && array[i] < 0)
            throw new IllegalArgumentException("Only use digits");
        else
            total += array[i] * Math.pow(10, array.length - i - 1);
    System.out.println(total);
    

    它适用于所有情况,但有数字的情况除外。确保您处理错误。

    (注意 Integer.MAX_VALUE)

    【讨论】:

      【解决方案5】:

      您可以使用BigInteger 来保存大于 int max size 的数字,并且可以避免 NumberFormatException。

      public static void main(String[] args) {
              int[] ary = {2,1,4,7,4,8,3,6,4,7};
      
              StringBuilder numBuilder = new StringBuilder();
              for(int num:ary) {
                  numBuilder.append(num);
              }
              BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
              BigInteger finalNum = new BigInteger(numBuilder.toString());
              if(finalNum.compareTo(maxInt)>0) {
                  //number is more the max size
                  System.out.println("number is more than int max size");
              }else {
                  int result = finalNum.intValueExact();
                  System.out.println(result);
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 2021-11-25
        • 2018-05-11
        • 2014-05-22
        • 1970-01-01
        相关资源
        最近更新 更多