How to convert an integer to an integer array in C#

3 Answers

0 votes
using System;
using System.Collections.Generic;
 
class Program
{
    public static int[] intToArray(int num) {
        List<int> numbers = new List<int>();
  
        do {
            numbers.Insert(0, num % 10);
            num /= 10;
        }
        while (num > 0);
  
        return numbers.ToArray();
    }
    static void Main() {
        int n = 792591;
  
        int[] arr = intToArray(n);

        Console.WriteLine(String.Join(", ", arr));
    }
}
 
 
 
/*
run:
 
7, 9, 2, 5, 9, 1
 
*/

 



answered Dec 12, 2021 by avibootz
edited Dec 12, 2021 by avibootz
0 votes
using System;

class Program
{
    public static int[] intToArray(int num) {
        int[] arr = new int[num.ToString().Length];
   
        for (int i = arr.Length - 1; i >= 0; i--) {
            arr[i] = num % 10;
            num /= 10;
        }

        return arr;
    }
    static void Main() {
        int n = 792591;
   
        int[] arr = intToArray(n);
 
        Console.WriteLine(String.Join(", ", arr));
    }
}
  
  
  
/*
run:
  
7, 9, 2, 5, 9, 1
  
*/

 



answered Dec 12, 2021 by avibootz
edited Jan 10 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        int n = 792591;
 
        int[] arr = n.ToString().Select(x => Convert.ToInt32(x) - 48).ToArray();

        Console.WriteLine(String.Join(", ", arr));
    }
}




/*
run:

7, 9, 2, 5, 9, 1

*/

 



answered Dec 12, 2021 by avibootz
...