views:

678

answers:

11

what would be the easiest way to convert an ArrayList of Integers to one int, with the 1st Integer in the list being the 1st number in the int, etc. in Java?

For example an ArrayList of Integers: 1 4 6 7 8 3 8
becomes the int value 1467838

+4  A: 

Assuming C# (you didn't specify :-), but the general algorithm will work in whatever language you need:

int num = 0;
for( int i = 0 ; i < list.Count ; i++ ) 
{
    num *= 10;
    num += (int)list[i];
}

Obviously the code assumes that the resulting number is small enough to be represented by int, and that each of the items in your ArrayList is between 0 and 9 both inclusive.

driis
+5  A: 

Note: easiest is not always most efficient. this is in java since you didn't specify a language. but you could do something like this:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(4);
list.add(6);

for (Integer x : list) {
    s += x.toString();
}

Integer finalResult = Integer.parseInt(s);

EDIT: to please all the people noting this in comments, if you're really worried about efficiency but for some reason want to use this string method, it should be done like this:

StringBuilder sb = new StringBuilder();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(4);
list.add(6);

String s;

for (Integer x : list) {
    sb.append(x.toString());
}

Integer finalResult = Integer.parseInt(sb.toString());

In the first example, StringBuilder was not used for simplicity's sake, because this looks like a homework assignment.

Alex Beardsley
thank you so much! very helpful, sorry about the really basic question though
before i get flamed for being the accepted answer, i will be the first to admit there are faster solutions out there. this seemed like the simplest for a beginner to understand.
Alex Beardsley
accepted answer because once I asked, and started looking at the answers, I realized that I already knew that this was what I was trying to do... and it's in java, which is what I wanted but (oops) forgot to say at first!
@Meg that's fine. just keep in mind that although you may not notice a difference in speed (i.e. premature optimization), the answers below that do it mathematically will most likely be faster.
Alex Beardsley
You should use StringBuilder to concatenate your string. Also final is a reserved word.
Steve Kuo
Not only are you using string operations, you're using += in a loop. This is pretty much textbook for how *not* to do it--but it does answer the question, and there's no way to know if it will be a bottleneck.
Michael Myers
hmkay... I shall try another way then
@mmyers and @Steve: yes I'm well aware. however this is a very simple example and to be honest it sounds like homework.
Alex Beardsley
it is, homework... sort ofand I wouldn't have asked except everyone else in my class has been looking at like i'm crazy when i tried to ask
Actually, you don't even have to call x.toString() explicitly. Anyway, as I said earlier, this does answer the question and efficiency was never mentioned. I'm just shooting for the simplest solution.
Michael Myers
@mmyers i'm actually slightly embarrassed to say that i never noticed that about StringBuilder, i.e. it does the String.valueOf conversion for you. very cool.
Alex Beardsley
+1  A: 

Only handles numbers up to 2 billion or so. Use long, long-long, or your favorite bigint class if you want bigger numbers. Won't work with negative numbers unless they're all negative.

int runningtotal = 0;
foreach(int i in myList) {
    runningtotal *= 10;
    runningtotal += i;
}
return runningtotal;
Aric TenEyck
A: 
int result = 0;
for(int i=list.Count - 1;i>=0;--i)
{
  result += list[i] * (int)(Math.Pow((double)10, (double)(list.Count - 1 - i)));
}

Also won't work with negative numbers...you could use Math.Abs() to handle that.

Jonas
A: 

Without knowing which language you want, I think your best approach is to find the sum of 1000000 + 400000 + 60000 + 7000 + 800 + 30 + 8

Marco Leung
A: 
int i = mylist
  .OfType<int>()
  .Aggregate( (soFar, next) => soFar*10 + next);

Well, that would work in C# anyway.

David B
A: 

I am assuming from your question that index 0 of the ArrayList is the most significant value. Your example show the first number being equivalent to 1,000,000.

You could either treat them as characters then concatenate them then parse back to Integer.

Or you can add each item to the result, then multiply the result by ten to set the magnitudes.

Or you can add each element's value * 10^(count-index); where count is the number of elements in the ArrayList.

John Christman
+10  A: 

The simplest way in Java is:

int total = 0;
for (Integer i : list) { // assuming list is of type List<Integer>
    total = 10*total + i;
}

For example, if the list consists of 1 4 6 7 8 3 8, you get:

  • total = 0
  • total = 10*0 + 1 = 1
  • total = 10*1 + 4 = 14
  • total = 10*14 + 6 = 146
  • ...
  • total = 10*146783 + 8 = 1467838

which is the correct answer.

Michael Myers
This is the best of the Java answers. To me, converting to a string and then converting back to an integer is not only inefficient, it's also convoluted.
Clint Miller
To be honest, in Java if you don't care about the efficiency of it, it's not that bad since all the conversions are run by native code. Though I'll definitely admit it's not the best way to do it.
Alex Beardsley
This breaks with any integer in the list > 9. I didn't see that constraint in the question, but the fact that the OP marked you as best indicates that all integers in the list are guaranteed to be <= 9.
Matt Kane
Yes, I took the question to mean that the list is a list of digits. If there are multiple-digit numbers in the list, this would break (silently).
Michael Myers
It also has silent overflow problems
oxbow_lakes
If your list is more than 10 digits, then yes, that would cause problems. Even `longs` max out at 19 digits.
Michael Myers
A: 

In Python! Just for fun:

i = int( "".join( [str(z) for z in x] ) )

Robbie
Whoops, this was before you specified a language. You said ArrayList so I assumed Java, but I just love Python so much.
Robbie
it's alright :-) if I ever write something in Python I'll remember it
A: 

In Haskell,

listToNumber = foldl (\a b -> a*10 + b) 0

In Python,

def list_to_number(some_list):
    return reduce(lambda x, y: x*10 + y, some_list, 0)
Clint Miller
Posted before the question specified a language.
Clint Miller
Also, being more concise, the Haskell can be reduced to foldl ((+) . (*) 10) 0
Clint Miller
A: 

Another solution, This will accept numbers > 9

List list = int num = Integer.parseInt(list.toString().replaceAll("\D",""));

Peter Lawrey