fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define INT_MAX 2147483647
  5. #define INT_MIN -2147483648
  6.  
  7.  
  8. void int2str(int i, char *s) {
  9. sprintf(s,"%d",i);
  10. }
  11.  
  12. char* extractStr(char* str, char buf[]){
  13. char* ptr;
  14. ptr = str;
  15. int tmp = 0;
  16. int idx = 0;
  17. int negativeIdx = -1;
  18. int isBufHasVaildNum = 0;
  19.  
  20. memset(buf,'\0',sizeof(buf));
  21. while(*ptr != '\0'){
  22. tmp = (int)(*ptr);
  23. if(tmp >= 48 && tmp <= 57){
  24. if(tmp != 48){
  25. buf[idx] = *ptr;
  26. isBufHasVaildNum = 1;
  27. idx++;
  28. }else{
  29. if(isBufHasVaildNum){
  30. buf[idx] = *ptr;
  31. idx++;
  32. }
  33. }
  34. }else if(tmp == 45){
  35. buf[idx] = *ptr;
  36. negativeIdx = idx;
  37. idx++;
  38. }else{
  39. if(tmp != 32 && tmp != 43)
  40. break;
  41. }
  42. ptr++;
  43. }
  44.  
  45. if(negativeIdx != -1 && buf[0] != '-'){
  46. int i = 0;
  47. for(i = negativeIdx; buf[i] != '\0' ;i++){
  48. buf[i] = '\0';
  49. }
  50. }
  51.  
  52. if(strcmp(buf,"-") == 0){
  53. buf[0] = '\0';
  54. }
  55.  
  56. return buf;
  57. }
  58.  
  59. int myAtoi(char * str){
  60.  
  61. char buf_1[64];
  62. char buf_2[64];
  63. int isPostiveBefore = 1;
  64. int isPostiveAfter = 1;
  65. long result;
  66.  
  67. str = extractStr(str, buf_1);
  68. if(*str == '\0')
  69. return 0;
  70.  
  71. if(*str == '-'){
  72. isPostiveBefore = 0;
  73. }
  74.  
  75. result = strtol(str,0,10);
  76. memset(buf_2,'\0',sizeof(buf_2));
  77. int2str(result, buf_2);
  78.  
  79. printf("%s\n",str);
  80. printf("%s\n",buf_2);
  81.  
  82. if(buf_2[0] == '-'){
  83. isPostiveAfter = 0;
  84. }
  85.  
  86. if(isPostiveBefore == 1 && isPostiveAfter == 0){
  87. result = INT_MAX;
  88. }
  89.  
  90. if(isPostiveBefore == 1 && isPostiveAfter == 1){
  91. if(strcmp(buf_2, str) != 0){
  92. result = INT_MAX;
  93. }
  94. }
  95.  
  96. if(isPostiveBefore == 0 && isPostiveAfter == 1){
  97. result = INT_MIN;
  98. }
  99.  
  100. if(isPostiveBefore == 0 && isPostiveAfter == 0){
  101. if(strcmp(buf_2, str) != 0){
  102. result = INT_MIN;
  103. }
  104. }
  105.  
  106. return result;
  107. }
  108.  
  109.  
  110.  
  111. int main(void) {
  112. // your code goes here
  113. int i = 0;
  114. i = myAtoi(" 0000000000012345678");
  115. printf("%d",i);
  116.  
  117. return 0;
  118. }
  119.  
  120.  
Success #stdin #stdout 0s 4280KB
stdin
Standard input is empty
stdout
12345678
12345678
12345678