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
voiditoa(int n,char*buffer) {longlong r = n;short iter =0;if (r <0) { r *=-1;buffer[iter++] ='-'; } stack<int> digits;longlong multiplier =10;longlong 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
voidreverse(char*str,int end) {int front =0; end -=1;while (front < end) {swap(str[front++],str[end--]); }}void__itoa(longlong n,char*buffer,int&iter) {if (n) { // core of the alg: take end of int, and then get rid of itbuffer[iter] = (n %10) +'0'; n /=10;__itoa(n, buffer,++iter); }}voiditoa(int n,char*buffer) {if (!n) {buffer[0] ='0'; buffer[1] ='\0';return; }longlong 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)