The implementation of the itoa and atoi functions should be a common question in the interview. Now, I want to write two functions to facilitate quick response when necessary.
[Cpp] // 0 indicates an error.
Int atoi (char * str)
{
Int len = lstrlenA (str );
Int ret = 0;
Int I = 0;
If ('-' = str [0] | '+' = str [0])
{
I = 1;
}
For (; I <len; ++ I)
{
If (str [I] <'0' | str [I]> '9 ')
{
Ret = 0;
Break;
}
Ret = ret * 10 + (str [I]-'0 ');
}
If ('-' = str [0])
{
Ret = ~ Ret + 1;
}
Return ret;
}
Char * itoa (int n, char * str, int radix)
{
Static char X [16] = {'0', '1 ',
'2', '3 ',
'4', '5 ',
'6', '7 ',
'8', '9 ',
'A', 'B ',
'C', 'D ',
'E', 'F'
};
Int I = 0;
While (1)
{
If (radix = 16)
Str [I] = X [n % radix];
Else
Str [I] = n % radix + '0 ';
If (n/= radix) = 0)
Break;
++ I;
}
For (int j = 0; j <(I + 1)/2; ++ j)
{
Char c = str [j];
Str [j] = str [I-j];
Str [I-j] = c;
}
Return str;
}
// Return 0, indicating an error
Int atoi (char * str)
{
Int len = lstrlenA (str );
Int ret = 0;
Int I = 0;
If ('-' = str [0] | '+' = str [0])
{
I = 1;
}
For (; I <len; ++ I)
{
If (str [I] <'0' | str [I]> '9 ')
{
Ret = 0;
Break;
}
Ret = ret * 10 + (str [I]-'0 ');
}
If ('-' = str [0])
{
Ret = ~ Ret + 1;
}
Return ret;
}
Char * itoa (int n, char * str, int radix)
{
Static char X [16] = {'0', '1 ',
'2', '3 ',
'4', '5 ',
'6', '7 ',
'8', '9 ',
'A', 'B ',
'C', 'D ',
'E', 'F'
};
Int I = 0;
While (1)
{
If (radix = 16)
Str [I] = X [n % radix];
Else
Str [I] = n % radix + '0 ';
If (n/= radix) = 0)
Break;
++ I;
}
For (int j = 0; j <(I + 1)/2; ++ j)
{
Char c = str [j];
Str [j] = str [I-j];
Str [I-j] = c;
}
Return str;
}
From Tiandao reward service