0

I want to know if there is a way in C# to convert an integer to an array of digits so that I can perform (Mathematical) operations on each digit alone.

Example: I need the user to input an integer i.e 123, 456 then the program creates two arrays of three elements {1,2,3}, {4,5,6}.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
myadav
  • 76
  • 1
  • 1
  • 10
  • 5
    Have you tried anything yet, had any ideas? You're going to get a string, so after you've validated that it is an integer you could just go through each character (number) and convert it to an integer. – tbddeveloper Oct 08 '14 at 19:23

3 Answers3

17

Off the top of my head:

int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
6

You could create such array (or List) avoiding string operations as follows:

int x = 123;
List<int> digits = new List<int>();
while(x > 0)
{
    int digit;
    x = Math.DivRem(x, 10, out digit);
    digits.Add(digit);
}
digits.Reverse();

Alternative without using the List and the List.Reverse:

int x = 456;
int[] digits = new int[1 + (int)Math.Log10(x)];
for (int i = digits.Length - 1; i >= 0; i--)
{
    int digit;
    x = Math.DivRem(x, 10, out digit);
    digits[i] = digit;
}

And one more way using ToString:

int x = 123;
int[] digits = Array.ConvertAll(x.ToString("0").ToCharArray(), ch => ch - '0');
Dmitry
  • 13,797
  • 6
  • 32
  • 48
1

You can use this and not convert to a string:

var digits = new List<int>();
var integer = 123456;
while (integer > 0)
{
  digits.Add(integer % 10);
  integer /= 10;
}

digits.Reverse();
Oleksandr Zolotarov
  • 919
  • 1
  • 10
  • 20