CtCI - Integer to String

CtCI - Integer to String

Given an unsigned integer, return the corresponding ASCII character representation without using language built-in features, for example, if the input integer is (int) 1234 the program has to return (string) "1234" as an array of characters or string.

In JavaScript we could simply (1234).toString() but one of the rules in the exercise is that we cannot use built-in language features like toString(). We have to find a way to separate each digit in the original number and convert it to its individual character representation, maybe using an array of numbers from zero to nine.

How do we separate 1 from 1234? We can divide the number by one thousand and then drop the decimals, but in order to do this we have to know the length of the number, in this case it has four digits so the length is a multiple of 1,000 but what if we pass a bigger number? We will not know its length so easily.

Lets go backwards, lets go from right-to-left and extract 4 dividing by ten, if the number is lower than then we can simply print the associated character from the number map, otherwise we will divide the number by ten multiple times until there are no more digits to translate.

1234 / 10         = 123.4
Math.floor(123.4) = 123
123 * 10          = 1230
1234 - 1230       = 4

As you can see above, if we divide the number by ten we will get the right-most digit as a decimal point, we need to revert that number back to an integer but dropping the decimal, there is no rule saying we cannot use built-in math functions so we will leverage Math.floor. The reverted number can be obtained by multiplying the result of the previous operation by the same number used for the division, in this case, the number ten. We will get a number that is slightly different than the original, the difference between them is the value that we will translate to characters. We will repeat this operation over and over until there is only one digit left.

func solution(number int) string {
    var dict = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

    if number < 10 {
        return dict[number]
    }

    var decimal int = number / 10
    var base int = int(math.Floor(float64(decimal)))
    var parent int = base * 10
    var diff int = number - parent

    return solution(base) + dict[diff]
}
Do you have a project idea? Let's make it together!