int array to int number in Java
Asked Answered
G

10

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.

Gouda answered 28/1, 2014 at 20:37 Comment(4)
Iterate over the array, convert each element to string and put it in a StringBuffer or just concatenate to string.Suicidal
Strings.... people is crazy or has nothing to do with computer programming at all. I have downvoted ALL answers related to strings.Angry
@Angry 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 inputGilbertson
Here is my algorithm: pastebin.com/yeymhQtAGouda
W
18

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.

Wifehood answered 28/1, 2014 at 20:40 Comment(5)
Glad someone suggested multiplying each by it's ten place rather than using a StringBuilder and parsing it back.Radiancy
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 ?Gouda
@Gouda 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 longGilbertson
And if this can help, I'm using an array initialised like this: int[] arr = {2, 15, 14, 10, 15, 21, 18};Gouda
@Gouda If you use a long as opposed to int It will work, see my edited answer.Gilbertson
L
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);
Lynch answered 28/1, 2014 at 20:39 Comment(2)
First method was by far the best I have seen thank u for thisThumbnail
it changed [1,0] to 1, which should be 10Oxysalt
C
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;
}
Caveman answered 28/1, 2014 at 20:42 Comment(14)
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 occuredGilbertson
@JavaDevil True... it's not clear what would be supposed to happen in that case.Caveman
It's the same here ! I'm getting this error: java.lang.NumberFormatException: For input string: "2151410152118"Gouda
@Gouda 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.Caveman
I already tried and I get the same error with a long variable. :(Gouda
@ValekHalfHeart I think you mean 2^31 -1 See docsGilbertson
@Gouda Did you use Integer.parseInt or Long.parseLong for the parsing?Caveman
@ValekHalfHeart nope... y'know my level in Java isn't really high and I didn't know this function an hour ago so nope, I didn't use any of the above.Gouda
In my code where it says Integer.parseInt you should change it to Long.parseLong if you're using longs. Also change the return type to long.Caveman
@ValekHalfHeart We're almost there except that I get a scientific writing of the number 85121215 like this: 8.5121215E7Gouda
@Gouda That's just how java expresses longs when they get large enough.Caveman
So now how do I do to "cut" the number every two figures like this: 85121215 becomes int [] arr ={85, 12, 12, 15}; ?Gouda
I'm getting an error and I don't get why. "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"Gouda
@Gouda I don't know why either. I cannot reproduce your error.Caveman
B
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.

Bull answered 28/1, 2014 at 20:49 Comment(0)
U
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.

Unsnap answered 28/1, 2014 at 21:5 Comment(1)
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.Gouda
M
1

BE SIMPLE!!!

public static int convertToInteger(int... arr) {
    return Integer.parseInt(Arrays.stream(arr)
                                  .mapToObj(String::valueOf)
                                  .collect(Collectors.joining()));
}
Mortimer answered 28/10, 2022 at 19:38 Comment(0)
G
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);
Gilbertson answered 28/1, 2014 at 20:41 Comment(6)
Sorry but I get an error when running: java.lang.NumberFormatException: For input string: "2151410152118"Gouda
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 errorGilbertson
1. Don't do this. 2. If you do, don't use +=, use an StringBuilderLoam
" 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?Angry
@Angry 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.Gilbertson
@Loam 1. Your point 1 and 2 are the same. 2. Yes If it was a larger array to deal with, StringBuilder for sure but any thing that long the OP has much bigger problems to deal withGilbertson
H
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");
}
Hyacinthhyacintha answered 23/9, 2015 at 14:11 Comment(0)
T
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();
}
Terrance answered 1/7, 2022 at 9:1 Comment(0)
C
-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();
    }
Carnahan answered 28/10, 2022 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.