Break an integer number into it's constituent digits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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