Created
November 4, 2012 09:27
-
-
Save atneik/4011054 to your computer and use it in GitHub Desktop.
atoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
#include <limits.h> | |
int myAtoi ( const char * str ){ | |
int number = 0; | |
int index = 0; | |
int length; | |
int isNeg = 0; | |
for(length = 0; str[length]!='\0'; length++); | |
if(str[0] == '-'){ | |
isNeg = 1; | |
index++; | |
length--; | |
} | |
for(; length > 0; index++){ | |
if(str[index] >= '0' && str[index] <= '9'){ | |
number += (str[index] - '0')*pow(10,length-1); | |
length--; | |
}else{ | |
fprintf(stderr, "Error! Not a numerical. "); | |
return -1; | |
} | |
} | |
if(isNeg){ | |
number *= -1; | |
} | |
return number; | |
} | |
int main(){ | |
char *testStr; | |
printf("%d\n",myAtoi("0021334")); | |
printf("%d\n",myAtoi("21334")); | |
printf("%d\n",myAtoi("-2334")); | |
printf("%d\n",myAtoi("-")); | |
printf("%d\n",myAtoi("0")); | |
printf("%d\n",myAtoi("")); | |
printf("%d\n",myAtoi("87p9")); | |
printf("%d\n",myAtoi("2-334")); | |
sprintf(testStr,"%d",INT_MAX); | |
printf("%s -> %d\n",testStr, myAtoi(testStr)); | |
sprintf(testStr,"%ld",(long)INT_MAX+1); | |
printf("%s -> %d\n",testStr, myAtoi(testStr)); | |
sprintf(testStr,"%d",INT_MIN); | |
printf("%s -> %d\n",testStr, myAtoi(testStr)); | |
sprintf(testStr,"%ld",(long)INT_MIN-1); | |
printf("%s -> %d\n",testStr, myAtoi(testStr)); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21334 | |
21334 | |
-2334 | |
0 | |
0 | |
0 | |
Error! Not a numerical. -1 | |
Error! Not a numerical. -1 | |
2147483647 -> 2147483647 | |
2147483648 -> -2147483648 | |
-2147483648 -> -2147483648 | |
-2147483649 -> -2147483648 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment