fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <limits.h>
  5.  
  6. /**
  7.  * @param s 字符串
  8.  * @return 整型
  9.  */
  10. int myAtou(char* s) {
  11. if (s == NULL) return 0;
  12.  
  13. int i = 0;
  14. int sign = 1;
  15. long result = 0; // 用 long 来检测溢出
  16.  
  17. // 1. 跳过前导空格
  18. while (s[i] == ' ') {
  19. i++;
  20. }
  21.  
  22. // 2. 检查正负号
  23. if (s[i] == '-' || s[i] == '+') {
  24. sign = (s[i] == '-') ? -1 : 1;
  25. i++;
  26. }
  27.  
  28. // 3. 转换数字直到非数字字符
  29. while (s[i] >= '0' && s[i] <= '9') {
  30. result = result * 10 + (s[i] - '0');
  31.  
  32. // 检查溢出
  33. if (sign == 1 && result > INT_MAX) {
  34. return INT_MAX;
  35. }
  36. if (sign == -1 && -result < INT_MIN) {
  37. return INT_MIN;
  38. }
  39.  
  40. i++;
  41. }
  42.  
  43. return (int)(sign * result);
  44. }
  45.  
  46. // 测试用例
  47. int main() {
  48. printf("myAtou(\"42\") = %d\n", myAtou("42"));
  49. printf("myAtou(\" -42\") = %d\n", myAtou(" -42"));
  50. printf("myAtou(\"413 with world\") = %d\n", myAtou("413 with world"));
  51. return 0;
  52. }
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
myAtou("42") = 42
myAtou("   -42") = -42
myAtou("413 with world") = 413