Skip to content

Instantly share code, notes, and snippets.

@atneik
Created November 4, 2012 09:27
Show Gist options
  • Save atneik/4011054 to your computer and use it in GitHub Desktop.
Save atneik/4011054 to your computer and use it in GitHub Desktop.
atoi
#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;
}
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