Converts an integer value to a null-terminated string stores the result in the array given by str parameter.
Challenge: Implement both recursive and iterative implementations of itoa.
Iterative
void itoa(int n, char *buffer) {
long long r = n;
short iter = 0;
if (r < 0) {
r *= -1;
buffer[iter++] = '-';
}
stack<int> digits;
long long multiplier = 10;
long long divisor = 1;
bool go = true;
while (go) {
if (multiplier > r) go = false;
int next = (r % multiplier) / divisor;
digits.push(next);
divisor = multiplier;
multiplier *= 10;
}
while (!digits.empty()) {
buffer[iter++] = digits.top() + '0';
digits.pop();
}
buffer[iter] = '\0';
}
Recursive
void reverse(char *str, int end) {
int front = 0;
end -= 1;
while (front < end) {
swap(str[front++], str[end--]);
}
}
void __itoa(long long n, char *buffer, int &iter) {
if (n) {
// core of the alg: take end of int, and then get rid of it
buffer[iter] = (n % 10) + '0';
n /= 10;
__itoa(n, buffer, ++iter);
}
}
void itoa(int n, char *buffer) {
if (!n) {
buffer[0] = '0'; buffer[1] = '\0';
return;
}
long long r = n;
int iter = 0;
__itoa(abs(r), buffer, iter);
if (n < 0)
buffer[iter++] = '-';
buffer[iter] = '\0';
reverse(buffer, iter);
}
My buddies implementation (credit goes to David Ibrahim)
void itoa2(long long n, char **str) {
if (n < 10) {
**str = '0' + n;
*(*str+1) = '\0';
return;
}
itoa2(n/10, str);
++*str;
**str = '0' + (n % 10);
*(*str+1) = '\0';
}
void itoa(int n, char *str) {
long long num = n;
if (num < 0) {
*str = '-';
++str;
num *= -1;
}
itoa2(num, &str);
}