Create a gist now

Instantly share code, notes, and snippets.

Break an integer number into it's constituent digits.
using System;
public class Program
{
public static void Main()
{
var result = BreakToDigits(56);
}
public static int[] BreakToDigits(int startingNumber)
{
if (startingNumber < 1)
{
throw new ArgumentException("Starting number must be > 0", "startingNumber");
}
if (startingNumber < 10)
{
return new int[2] { 0, startingNumber };
}
double logNum = Math.Log10(startingNumber);
int numDigits = (int)Math.Floor(logNum + 1);
var digits = new int[numDigits];
int n = startingNumber;
int y;
int index = numDigits - 1;
while (n != 0)
{
y = n % 10;
digits[index--] = y;
n /= 10;
}
return digits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment