1. Implementation of itoa
// 1234 → 4321 storage: str = n % radix, n = n/radix) → 1234
// Todo: Just write down the content containing negative numbers.
Char * my_itoa2 (int num, char * string, int radix)
{
Char * str = string;
// Obtain the flipped string
While (num)
{
* Str = num % radix + '0'; // * str = num % radix-'0'; it is wrong, haha.
// Cout <* str <endl;
Num = num/radix;
Str ++;
}
* Str = '\ 0 ';
Char temp;
Int len = strlen (str );
For (int I = 0; I <len/2; I ++)
{
Temp = str [I];
Str [I] = str [len-1-i];
Str [len-1-i] = temp;
}
Return string;
}
2 atoi implementation
// Num = num * 10 + * str;
// Todo: consider the situation where the border is crossed.
Int my_atoi (char * str)
{
If (str = NULL) return 0;
Int num = 0, flag = 1;
If (* str = '-')
{
Flag =-1;
}
Else
{
Num = * str-'0 ';
}
Str ++;
// While (* st> = '0' & * str <= '9 ')
While (* str! = '\ 0 ')
{
Num = num * 10 + * str-'0 ';
Str ++;
}
Return num * flag;
}
3 test code
Int main ()
{
Char * s = "-123567890 ";
Cout <my_atoi (s) <endl;
Int a = 1234;
// * Char str [20] = {'\ 0'}; // pre-defined
Char * str = new char [20];
Str = my_itoa2 (a, str, 10 );
Cout <str <endl;
Return 0;
}