How to concatenate elements of an array into an integer
There is a say arr array with elements
6,5,1,0,9
I want an integer
a=65109
and
b=90156
+3
bhishaj
source
to share
4 answers
int arr[] = {6,5,1,0,9};
int result = 0,reverse = 0;
for (int i = 0; i < arr.length; i++) {
result= result*10 + arr[i];
reverse = reverse*10+arr[arr.length-1-i];
}
System.out.println(result);//number 65109
System.out.println(reverse);//number 90156
+6
Ali
source
to share
StringBuilder builder = new StringBuilder();
for(int i = 0;i<arr.length;i++){
builder.append(arr[i]);
}
long a = Long.parseLong(builder.toString());
long b = Long.parseLong(builder.reverse().toString());
System.out.println(a);
System.out.println(b);
+6
Pravin
source
to share
You can get it using the valueOf () method of the String class and parseXXX () of the Number class. Sample snippet below:
class Test{
public static void main(String[] args){
int[] arr={6,5,1,0,9};
String str="";
for(int i=0;i<arr.length;i++){
int x=arr[i];
str=str+String.valueOf(x);
}
int concatenated=Integer.parseInt(str);
System.out.println(concatenated);
}
}
For the reverse part, modify the condition as:
for(int i=arr.length-1;i>=0;i--)
Now the for loop will iterate in reverse order in the array.
+2
jcool
source
to share
IN Java 8
code:
List<Integer> list = Arrays.asList(6, 5, 1, 0, 9);
int value = Integer.parseInt(list.stream()
.map(i -> Integer.toString(i))
.reduce("", String::concat));
System.out.println(value);
Collections.reverse(list);
int ReverseValue = Integer.parseInt(list.stream()
.map(i -> Integer.toString(i))
.reduce("", String::concat));
System.out.println(ReverseValue);
output:
65109 90156
0
Kick Buttowski
source
to share