Problem
Convert integer to string
Solution
If number less than zero: Multiply number by –1 Set negative flag While number not equal to 0 Add '0' to number % 10 and write this to temp buffer Integer divide number by 10 If negative flag is set Write '-' into next position in temp buffer Write characters in temp buffer into output string in reverse order:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
char* iitoa(int num)
{
static char str[100];
char *p = str;
int n = num;
if(n == 0){
*p = '0';
*p = '\0';
}
else{
if(num < 0){
*p = '-';
p ++;
num = -num;
}
n = num;
int len = 0;
while(n){
len ++;
n /= 10;
}
*(p + len) = '\0';
len --;
n = num;
while(n){
*(p + len) = n % 10 + '0';
n /= 10;
len --;
}
}
return str;
}
int main(int argc, char* argv[])
{
for(int i = -2000; i < 2000; i += 499){
cout << i << " -- " << iitoa(i) << endl;
}
return 0;
}