gpt4 book ai didi

java - 如何将int数组转换为int

转载 作者:行者123 更新时间:2023-12-01 07:17:22 24 4
gpt4 key购买 nike

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

如何将生成的 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
}

}

最佳答案

给定数组

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. 的方法
  4. 现在,我们将这个字符串转换为long。您可以阅读更多有关来自文档 here 的流

我们在这里使用 long 是为了防止数字太大而无法包含在 int 中

关于java - 如何将int数组转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com