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. // 测试用例1
  49. printf("测试用例1: s = \"42\"\n");
  50. printf("期望输出: 42\n");
  51. printf("实际输出: %d\n\n", myAtou("42"));
  52.  
  53. // 测试用例2
  54. printf("测试用例2: s = \"-42\"\n");
  55. printf("期望输出: -42\n");
  56. printf("实际输出: %d\n\n", myAtou("-42"));
  57.  
  58. // 测试用例3
  59. printf("测试用例3: s = \"4193 with words\"\n");
  60. printf("期望输出: 4193\n");
  61. printf("实际输出: %d\n\n", myAtou("4193 with words"));
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
测试用例1: s = "42"
期望输出: 42
实际输出: 42

测试用例2: s = "-42"
期望输出: -42
实际输出: -42

测试用例3: s = "4193 with words"
期望输出: 4193
实际输出: 4193