0

After finding the individual digits of a number by remainder procedure, the numbers are saved in an array. What I want now is to take the individual elements of this array and make a single integer value of it.

eg.

int a = 4400

digits saved in array by using recursion (4400/10) : let array be arr[]

arr[0]=0;
arr[1]=0;
arr[2]=4;
arr[3]=4;

final value:

int b= 4400 (by combining elements of array)

So I want to know if there is any way to combine the array elements to a single integer value ?

san A
  • 177
  • 2
  • 13

3 Answers3

3

Just multiply and add the digits:

int result = 1000 * arr[3] + 100 * arr[2] + 10 * arr[1] + arr[0];

Or, if you need it to work for any length of array (up to the number of digits in Integer.MAX_VALUE):

int result = 0;
for (int i = arr.length - 1; i >= 0; --i) {
  result = 10*result + arr[i];
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Using `i--` should be avoided in loops when possible, because it goes even further against what you could consider human mathematical and logical reasoning. Just leaving this comment here for new users searching same answer. – The Law Nov 09 '15 at 11:23
2

I would use a stringbuilder.

StringBuilder builder = new StringBuilder();
builder.append(arr[3]);
builder.append(arr[2]);
builder.append(arr[1]);
builder.append(arr[0]);
System.out.println("Combined value is: " + Integer.parseInt(builder.toString());
JBiss
  • 131
  • 10
0

How about using simple loop and multiplication (assuming you know basic math)

int b = 0;
int z = 10;
for (int i = 1; i <= arr.length; i++) {
   b = (int) (b + (arr[i - 1] * Math.pow((double) z, i - 1)));
}
The Law
  • 344
  • 3
  • 20