52 lines
959 B
C
52 lines
959 B
C
#include <stdio.h>
|
|
#include <ctype.h>
|
|
#include <limits.h>
|
|
|
|
int myatoi(char *instr) {
|
|
if (instr == NULL) {
|
|
return 0;
|
|
}
|
|
|
|
while (isspace((unsigned char)*instr)) {
|
|
instr++;
|
|
}
|
|
|
|
int sign = 1;
|
|
if (*instr == '+') {
|
|
instr++;
|
|
} else if (*instr == '-') {
|
|
sign = -1;
|
|
instr++;
|
|
}
|
|
|
|
long result = 0;
|
|
while (*instr >= '0' && *instr <= '9') {
|
|
int digit = *instr - '0';
|
|
|
|
if (sign > 0) {
|
|
if (result > (LONG_MAX - digit) / 10) {
|
|
return INT_MAX;
|
|
}
|
|
} else {
|
|
if (-result < (LONG_MIN + digit) / 10) {
|
|
return INT_MIN;
|
|
}
|
|
}
|
|
|
|
result = result * 10 + digit;
|
|
instr++;
|
|
}
|
|
|
|
return (int)(result * sign);
|
|
}
|
|
|
|
int main() {
|
|
printf("myatoi(\"1\") = %d\n", myatoi("1"));
|
|
printf("myatoi(\"42\") = %d\n", myatoi("42"));
|
|
printf("myatoi(\"-105\") = %d\n", myatoi("-105"));
|
|
printf("myatoi(\" -12abc34\") = %d\n", myatoi(" -12abc34"));
|
|
printf("myatoi(\"9999999999999\") = %d (overflow)\n", myatoi("9999999999999"));
|
|
|
|
return 0;
|
|
}
|