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)
?
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)
?
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();
}
I know there are probably better answers than this, but here is another version:
You can use yield return
to return the digits in ascending order (according to weight, or whatever it is called).
public static IEnumerable<int> Digits(this int number)
{
do
{
yield return number % 10;
number /= 10;
} while (number > 0);
}
12345 => 5, 4, 3, 2, 1
Another alternative which don't uses recursion and uses a Stack that avoids reallocation on every insert (at least for the first 32 digits):
var list = new Stack<int>(32);
var remainder = 123456;
do
{
list.Push(remainder % 10);
remainder /= 10;
} while (remainder != 0);
return list.ToArray();
And yes, this method also works for 0 and negative numbers.
Interestingly, give this algorithm a negative number -123456 and you will get {-1, -2, -3, -4, -5, -6}
Update: switched from using List to Stack since this automatically gives the correct order.
var x = new Stack<int>();
do
{
x.Push(i % 10);
i /= 10;
} while (i > 0);
return x.ToArray();
In short: use loop which divide number modulo 10 (%) to get reminder (each digit) and put it into array.
Strings and can fun (some of the other options would be faster... but this is pretty easy)
var @is = 987654321.ToString().Select(c => c - 48).ToArray();
This does convert to string and iterate over the characters, but it does it sort of automatically and in a one-liner:
var i = 987654321;
var @is = i.ToString().Select(c => c - '0').ToArray();