- Home /
How to convert and integer into an Array of his digits
Hi guys,
I'm working on a simple game and I have an interger made of X digits let's say 0123456789. now what I would like to do is to obtain an array that has X spaces in which each one contain only one of the digits of the integer. If it easier It will be fine even with a string since than I can convert string into integer.
Thank you.
Answer by mattyman174 · May 15, 2014 at 12:11 PM
Try this on for size.
public static int[] IntToIntArray(int num)
{
if (num == 0)
return new int[1] { 0 };
List<int> digits = new List<int>();
for (; num != 0; num /= 10)
digits.Add(num % 10);
int[] array = digits.ToArray();
System.Array.Reverse(array);
return array;
}
Modulo is so wonderful :)
Essentially all your doing here is dividing the original given integer by 10 each time thereby forcing each individual number from the end to beginning into a decimal and using modulo we can just get that number each time.
Then simply reverse the array created and you have the number as an int array.
Just to note some constraints on this solution though, you cant give it negative integers and be careful you dont start trying to feed it something bigger than an integer, like a long.
This was super handy! Thanks :) $$anonymous$$odulo is cool :D
One small detail is that C#'s modulo operator returns a negative number for negative values. If you want the digits without sign, you should first $$anonymous$$athf.Abs()
the value before adding it to digits
.
Answer by Naveen Kumar · May 15, 2014 at 11:55 AM
U can Write Like
lets say no = 123456789; int rem = 0; vector arr;
While( no ) {
rem = no%10;
arr.pushback( rem );
no = no/10;
}
And U can have all the digits in reverse order
Answer by shadabeqbal · Mar 20, 2018 at 07:34 AM
static int[] Int_to_array(int n)
{
int j = 0;
int len = Integer.toString(n).length();
int[] arr = new int[len];
while(n!=0)
{
arr[len-j-1]=n%10;
n=n/10;
j++;
}
return arr;
}
Answer by Jamal94 · Aug 14, 2020 at 04:01 PM
int[] toArray(int n) { int[] arr = new int[len(n)]; for (int i = arr.length - 1; i >= 0; i--) { arr[i] = n % 10; n = n / 10; } return arr; } int len(int n) { int count = 0; while (n > 0) { n = n / 10; count++; } return count; }
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Array of GameObjects - JS 1 Answer
Array iteration problem 1 Answer
Sequential GameObject Activation 2 Answers
C# Children and SubChildren Null Reference Exception 1 Answer