例如,輸入“123”,應輸出整數123,輸入“-12”,應輸出-12。
#include<stdio.h>
#include<assert.h>
int Myatoi(const char* str)
{
int tmp = 0;
if (*str == '-')//整數為負數的情況
{
str++;
while (*str != '\0' && *str <= '9' && *str >= '0')
{
int i = *str - 48;
tmp = tmp * 10 + i;
str++;
}
return 0 - tmp;
}
else if (*str == '+')
{
str++;
}
while (*str != '\0' && *str <= '9' && *str >= '0')
{
int i = *str - '0';
tmp = tmp * 10 + i;
str++;
}
return tmp;
}
int main()
{
printf("%d\n", Myatoi("123"));
printf("%d\n", Myatoi("+1234a"));
printf("%d\n", Myatoi("-123"));
printf("%d\n", Myatoi("0"));
return 0;
}
調試結果如下:
