# 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.

```cpp
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

```cpp
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;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/recursion-and-dynamic-programming/recursive_string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
