Snippets

Craig Phillips Break an integer number into its constituent digits.

Created by Craig Phillips
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;
	}
}

Comments (0)