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 ?

2
  • 2
    Multiplication and addition. Commented Nov 9, 2015 at 11:05
  • There is a way. It is similar to the way you decomposed it. Please make a try. Commented Nov 9, 2015 at 11:05

3 Answers 3

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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());

3 Comments

As you can see in the question final value should be an int again.
The result is not an int, and the digits are reversed.
I have edited the answer
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)));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.