Recursive to_string

Implement a recursive "int_to_string" function

Ex.

12341243123 -> "12341243123"
  • This approach is actually O(n^2) since I always insert to the front of the string shifting back 1,2,3...4 elements at a time.

int at_num(int num, int at) {
    return (num / int(pow(10, at))) % 10;
}

void int_to_string(int n, string &str, int at) {
    int i = at_num(n, at);
    if (i != 0) {
        str.insert(0, to_string(i));
        return int_to_string(n, str, ++at);
    }
}

string int_to_string(int n) {
    string result = "";
    int_to_string(n, result, 0);
    return result;
}

int main() {
    cout << int_to_string(1234);
    pause();
}
  • O(n) approach with a few improvements:

    • const correctness

    • demonstration of static variable in use

    • string size reservation

    • no use of function to_string in std

int digit_at(const long long num, const int at, const size_t size)
{
    return int(num / pow(10, size - at - 1)) % 10;
}

void to_string(const long long num, const int &size, string &final)
{
    static int count = 0;
    if (count < size) {
        final += digit_at(num, count++, size) + '0';
        to_string(num, size, final);
    }
    count = 0; // otherwise next function call maintain this.
}

string my_to_string(const long long num)
{
    string final;
    const int size = num_digits(num);
    final.reserve(size);
    to_string(num, size, final);
    return final;
}

int main()
{
    cout << my_to_string(1234) << endl;
    cout << my_to_string(123456) << endl;
    cout << my_to_string(123456789) << endl;
}

Last updated