10

I'm new on this site and, if I'm here it's because I haven't found the answer anywhere on the web and believe me: I've been googling for quite a time but all I could find was how to convert a number to an array not the other way arround. I'm looking for a simple way or function to convert an int array to an int number. Let me explain for example I have this :

int[] ar = {1, 2, 3};

And I want to have this:

int nbr = 123;

In my head it would look like this (even if I know it's not the right way):

int nbr = ar.toInt(); // I know it's funny

If you have any idea of how I could do that, that'd be awesome.

4
  • Iterate over the array, convert each element to string and put it in a StringBuffer or just concatenate to string. Commented Jan 28, 2014 at 20:40
  • 1
    Strings.... people is crazy or has nothing to do with computer programming at all. I have downvoted ALL answers related to strings. Commented Jan 28, 2014 at 21:15
  • @Manu343726 How does it not have anything to do with programming... it gets the answer required and is a short piece of code, not necessary the most efficient, but that was not asked for. Even the most upvoted answer is not correct for input...but thats OPs fault of proving misguied input Commented Jan 28, 2014 at 21:23
  • Here is my algorithm: pastebin.com/yeymhQtA Commented Jan 28, 2014 at 21:36

10 Answers 10

19

Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.

  • Result: 0
  • Loop 1: Result * 10 => 0, Result + 1 => 1
  • Loop 2: Result * 10 => 10, Result + 2 => 12
  • Loop 3: Result * 10 >= 120, Result + 3 => 123

This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.

Sign up to request clarification or add additional context in comments.

5 Comments

Glad someone suggested multiplying each by it's ten place rather than using a StringBuilder and parsing it back.
In fact, I'm not able to get none of the below algorithms working. So could you clarify what's above and tell me how I could right that in java ?
@gotgot1995 Even if you get this method working correctly, for your input using the type of int will not work correctly. Your input is to large to be held in an int. You need to use a type of long
And if this can help, I'm using an array initialised like this: int[] arr = {2, 15, 14, 10, 15, 21, 18};
@gotgot1995 If you use a long as opposed to int It will work, see my edited answer.
6

You have to cycle in the array and add the right value. The right value is the current element in the array multiplied by 10^position.

So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....

    int res=0;
    for(int i=0;i<ar.length;i++) {
         res=res*10+ar[i];
    }

Or

   for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
        res+=ar[i]*Math.pow(10, exp);

2 Comments

First method was by far the best I have seen thank u for this
it changed [1,0] to 1, which should be 10
4

First you'll have to convert every number to a string, then concatenate the strings and parse it back into an integer. Here's one implementation:

int arrayToInt(int[] arr)
{
    //using a Stringbuilder is much more efficient than just using += on a String.
    //if this confuses you, just use a String and write += instead of append.
    StringBuilder s = new StringBuilder(); 

    for (int i : arr)
    {
         s.append(i); //add all the ints to a string
    }

    return Integer.parseInt(s.toString()); //parse integer out of the string
}

Note that this produce an error if any of the values past the first one in your array as negative, as the minus signs will interfere with the parsing.

This method should work for all positive integers, but if you know that all of the values in the array will only be one digit long (as they are in your example), you can avoid string operations altogether and just use basic math:

int arrayToInt(int[] arr)
{
    int result = 0;

    //iterate backwards through the array so we start with least significant digits
    for (int n = arr.length - 1, i = 1; n >= 0; n --, i *= 10) 
    {
         result += Math.abs(arr[n]) * i;
    }

    if (arr[0] < 0) //if there's a negative sign in the beginning, flip the sign
    {
        result = - result;
    }

    return result;
}

This version won't produce an error if any of the values past the first are negative, but it will produce strange results.

There is no builtin function to do this because the values of an array typically represent distinct numbers, rather than digits in a number.

EDIT:

In response to your comments, try this version to deal with longs:

long arrayToLong(int[] arr)
{
    StringBuilder s = new StringBuilder(); 

    for (int i : arr)
    {
         s.append(i);
    }

    return Long.parseLong(s.toString());
}

Edit 2:

In response to your second comment:

int[] longToIntArray(long l)
{
    String s = String.valueOf(l);   //expand number into a string

    String token;

    int[] result = new int[s.length() / 2]; 

    for (int n = 0; n < s.length()/2; n ++) //loop through and split the string
    {
        token = s.substring(n*2, (n+2)*2);
        result[n] = Integer.parseInt(token); //fill the array with the numbers we parse from the sections
    }

    return result;
}

14 Comments

Note that this will fail if any of the values in your array as negative as it would for anyones answer... would probably be a case of invalid input if it occured
@JavaDevil True... it's not clear what would be supposed to happen in that case.
It's the same here ! I'm getting this error: java.lang.NumberFormatException: For input string: "2151410152118"
@gotgot1995 The maximum value of a int is 2^32-1, or 4294967295. Your number is too large. Use a long or a java.math.BigInteger if you need numbers that large.
I already tried and I get the same error with a long variable. :(
|
3

yeah you can write the function yourself

int toInt(int[] array) {
    int result = 0;
    int offset = 1;
    for(int i = array.length - 1; i >= 0; i--) {
        result += array[i]*offset;
        offset *= 10;
    }
    return result;
}

I think the logic behind it is pretty straight forward. You just run through the array (last element first), and multiply the number with the right power of 10 "to put the number at the right spot". At the end you get the number returned.

Comments

2
int nbr = 0;
for(int i = 0; i < ar.length;i++)
    nbr = nbr*10+ar[i];

In the end, you end up with the nbr you want.

For the new array you gave us, try this one. I don't see a way around using some form of String and you are going to have to use a long, not an int.

int [] ar = {2, 15, 14, 10, 15, 21, 18};
long nbr = 0;
double multiplier = 1;
for(int i = ar.length-1; i >=0 ;i--) {
    nbr += ar[i] * multiplier;
    multiplier = Math.pow(10, String.valueOf(nbr).length());
}

If you really really wanted to avoid String (don't know why), I guess you could use

multiplier = Math.pow(10,(int)(Math.log10(nbr)+1));

which works as long as the last element in the array is not 0.

1 Comment

If my array is initialised like this: int[] arr = {2, 15, 14, 10, 15, 21, 18}; your algorithm gives me this: 3651728 but I would like this 2151410152118.
1

BE SIMPLE!!!

public static int convertToInteger(int... arr) {
    return Integer.parseInt(Arrays.stream(arr)
                                  .mapToObj(String::valueOf)
                                  .collect(Collectors.joining()));
}

Comments

0

Use this method, using a long as your input is to large for an int.

long r = 0;
for(int i = 0; i < arr.length; i++)
{
    int offset = 10;
    if(arr[i] >= 10)
        offset = 100;
    r = r*offset;
    r += arr[i];
}

This checks if the current int is larger than 10 to reset the offset to 100 to get the extra places required. If you include values > 100 you will also need to add extra offset.


Putting this at end of my post due to all the downvotes of Strings...which is a perfectly legitimate answer...OP never asked for the most efficient way to do it just wannted an answer

Loop your array appending to a String each int in the array and then parse the string back to an int

String s = "";
for(int i = 0; i < arr.length; i++)
       s += "" + arr[i];
int result = Integer.parseInt(s);

From your comment the number you have is too long for an int, you need to use a long

String s = "";
for(int i = 0; i < arr.length; i++)
       s += "" + arr[i];
long result = Long.parseLong(s);

6 Comments

Sorry but I get an error when running: java.lang.NumberFormatException: For input string: "2151410152118"
That's because that results in a Number which is too large to be held by an int, you will need to use a long. The reason you wouldn't get this exception when using the other methods of adding is that you will be getting a rollover error
1. Don't do this. 2. If you do, don't use +=, use an StringBuilder
" due to all the downvotes of Strings...which is a perfectly legitimate answer..." No, thats not a reasonable answer at all. You can perform floating-point multiplication storing number bits as two strings and playing around with them... Works, but.... are you kidding me?
@Manu343726 I never said it was reasonable, I said it was legitimate. Who said anything about floating-point multiplication. The point is for the given example in the question its valid. The OP is not interested in efficiency.
|
0

If you can use Java 1.8, stream API makes it very simple:

@Test
public void arrayToNumber() {
    int[] array = new int[]{1,2,3,4,5,6};
    StringBuilder sb = new StringBuilder();

    Arrays.stream(array).forEach(element -> sb.append(element));

    assertThat(sb.toString()).isEqualTo("123456");
}

Comments

0

you can do it that way

public static int[] plusOne(int[] digits) {
    StringBuilder num= new StringBuilder();
    PrimitiveIterator.OfInt primitiveIterator = Arrays.stream(digits)
            .iterator();
    while (primitiveIterator.hasNext()) {
        num.append(primitiveIterator.nextInt());
    }
    int plusOne=Integer.parseInt(String.valueOf(num))+1;
    return Integer.toString(plusOne).chars().map(c -> c-'0').toArray();
}

Comments

-1

this also possible to convert an Integer array to an int array

    int[] result = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        result[i] = arr[i].intValue();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.