atoi请高手来作答

来源:百度知道 编辑:UC知道 时间:2024/06/04 22:23:47
Write a function in C or C++ that reads an ascii character string and returns the integer value that it represents. The function should ignore leading whitespace and stop conversion at the first non digit character. Where conversion is not possible, the function should return 0 and indicate an error condition.
Example:
int atoi(const char *s, int *error)
{

}
Input
Error? Returns
“123” No 123
“-1” No -1
“456abc” No 456
“abc” Yes n/a
“0003” No 3
“” Yes n/a
“0” No 0
“ 123” No 123

The solution should not use any C/C++ runtime library routines such as “scanf”.
Comment the code so that the interviewer may understand decisions you have taken when writing the code. You should spend no more than 30 minutes on this task.

int atoi(const char *s, int *error)
{
int RetVal = 0;
do
{
char *pTmp = s;
*error = 1;
while(NULL != pTmp)
{
char ch = *pTmp;
if(0 == *error)
{
if(!IsDigit(ch))
break;
}
else
{
if(!IsDigit(ch))
continue;
}
*error = 0;
RetVal = RetVal *10 + (int)ch - 48;/*48 是‘0’的ASCII码值*/
pTmp++;
}
}while(0);
return RetVal;
}

char* s="123"
int result = 0;
for(int i=0; i<strlen(s); i++)
{
result += ( s[i]-'0' ) * power(10, i);
}

return result;