recursive function to reverse string

This commit is contained in:
Sandipsinh Rathod 2024-10-10 20:04:26 -04:00
parent d02753efb0
commit 2b6b1ee2bb

@ -99,6 +99,23 @@ bool isValidPlayer(char c) {
return c >= 'A' && c <= 'Z' && c != 'X';
}
void swapChar(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}
// Recursively reverse a string
void reverseString(string &str, int start, int end) {
if (start >= end) {
return;
}
swapChar(str[start], str[end]);
reverseString(str, start + 1, end - 1);
}
string toString(int x) {
if (!x) return "0";
@ -107,7 +124,7 @@ string toString(int x) {
result.push_back(x % 10 + '0');
x /= 10;
}
reverse(all(result));
reverseString(result, 0, result.size() - 1);
return result;
}