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

Last updated

Was this helpful?