Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to turn an int into an array of ints of each digit?

Tags:

Say I have

var i = 987654321; 

Is there an easy way to get an array of the digits, the equivalent of

var is = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 

without .ToString()ing and iterating over the chars with int.Parse(x)?

like image 266
Andrew Bullock Avatar asked May 06 '09 11:05

Andrew Bullock


People also ask

Can Integer convert to array?

Get the set of integers. Create an object of Primitive int by ArrayUtils. toPrimitive() method of Apache Commons Lang's library. Convert this primitive int to array of integer by use of toArray() method.

How do you convert an array of integers into a single Integer in Java?

We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.

How do you store each digit of a number in an array in Java?

int[] array = new int[6]; int number = 675421 array[0] = 6; array[1] = 7; array[2] = 5; array[3] = 4; array[4] = 2; array[5] = 1; I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!


1 Answers

public Stack<int> NumbersIn(int value) {     if (value == 0) return new Stack<int>();      var numbers = NumbersIn(value / 10);      numbers.Push(value % 10);      return numbers; }  var numbers = NumbersIn(987654321).ToArray(); 

Alternative without recursion:

public int[] NumbersIn(int value) {     var numbers = new Stack<int>();      for(; value > 0; value /= 10)         numbers.Push(value % 10);      return numbers.ToArray(); } 
like image 64
Garry Shutler Avatar answered Sep 25 '22 05:09

Garry Shutler