Question: Without using any system-provided function [eg. Int32.ToString() ], write a function that takes an integer and returns a string of the value.

Answer: This is fairly trivial but a seemingly common question to throw at programmers. All you need to do is apply some modular arithmetic to iterate over each digit fetching the string value as you go. The edge cases for negative numbers and 0 still seem to catch many people out! It's trivial to extend this algorithm to bases other than 10.

Here's some code in C# to do it:

public static string ConvertInt(int i)
{
    var digits = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    var result = "";
 
    if (i == 0) return "0";
 
    bool isNegative = (i < 0);
 
    if (isNegative)
        i = i * -1;
 
    while (i != 0)
    {
        result = digits[i % 10] + result;
        i = (i - i % 10) / 10;
    }
 
    if (isNegative)
        result = "-" + result;
 
    return result;
}
Bookmark and Share