Itoa
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
My buddies implementation (credit goes to David Ibrahim)
Testing
Last updated
Was this helpful?