Here is a more functional approach using recursion and returns back the formatted string rather than writing to Console.
static
string
FormatDigits(
int value)
{
return
value < 10
? value.ToString()
: String.Format(
"{0} {1}",
FormatDigits(value / 10),
value % 10);
}
Update: Some explanation for those unfamiliar with recursion or find this code difficult to digest. Recursion provides a way to reduce the problem into a set of smaller problems and simpler solutions.
There are 2 cases here.
- If the value < 10 (exactly one digit)
Simply convert the digit to a string, (value.ToString()) and return it - If the value >= 10 (more than one digit)
The value % 10 will give the last digit, use this value as the last character of the result (with a space prefix) the " {1}" part of the string format.
The problem is now reduced to doing the same thing all over again, this time with a value without the last digit (value / 10) and placing the result in the "{0}" part of the format string.
Update 2: Don't like the string format or find it difficult to understand? Here is another refactor.
static
string
FormatDigits(
int value)
{
return
value < 10
? value.ToString()
: FormatDigits(value / 10) + " " + FormatDigits(value % 10);
}