Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How can I convert an Integer to list of numbers? For example:

781049 ==> {7, 8, 1, 0, 4, 9}

What are the possible ways of doing this? How well they compare performance-wise? Is a compiled version faster than IntegerDigits? How to convert huge amounts of large integers to digit form?

share|improve this question
5  
Have a look at IntegerDigits. –  b.gatessucks Apr 10 '13 at 11:39
    
Or have a look at ToString, Characters and ToExpression, in this order. –  István Zachar Apr 10 '13 at 11:47
    
2  
Sorry all: per this meta discussion, I took the liberty to make a perhaps more useful question. –  István Zachar Apr 10 '13 at 11:53
2  
For speed, IntegerDigits is really the way to go about this. –  Daniel Lichtblau Apr 10 '13 at 13:37
add comment

2 Answers

This is pretty easy if you understood that we live in a world of base 10 and the principles of division with rest:

n = 781049;
Rest@Reverse[Flatten@Last@Reap@FixedPointList[(Sow[Mod[#, 10]]; Quotient[#, 10]) &, n]]
(* {7, 8, 1, 0, 4, 9} *)

or as J.M. suggested with one call to get the quotient and the remainder

With[{n = 781049}, Reverse[Reap[NestList[Block[{q, r}, 
 {q, r} = QuotientRemainder[#, 10]; Sow[r]; q] &, n, IntegerLength[n]]][[-1, 1]]]]

If you really prefer shorter methods, than you could go with

IntegerDigits[n]

or maybe

ToExpression@StringCases[ToString[n], DigitCharacter]

if you like strings. Without giving explicit timings you can safely assume, that every function will be slower than IntegerDigits.

share|improve this answer
    
It might be nice to add timings to this question, given that István Zachar emphasized this. (+1) –  Mr.Wizard Apr 10 '13 at 14:23
add comment
f[n_ /; n < 10] := {n};
f[n_] := f[Floor[n/10]]~Join~{n~Mod~10};

f[n0_] := Block[{n = n0, r = {}},
  While[n != 0,
   r = {n~Mod~10}~Join~r;
   n = Floor[n/10]];
  r
 ]

f /@ {123, 142857, 9876}
(*{{1, 2, 3}, {1, 4, 2, 8, 5, 7}, {9, 8, 7, 6}}*)
share|improve this answer
1  
Floor[n/10] is better written as Quotient[n, 10]. –  J. M. Apr 10 '13 at 14:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.