Leetcode: String to Integer (atoi)

女爷i 2022-08-06 15:15 81阅读 0赞

题目:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

参考代码:

  1. #define INT_MAX 2147483647
  2. #define INT_MIN (-INT_MAX-1)
  3. class Solution
  4. {
  5. public:
  6. int atoi(const char *str)
  7. {
  8. if (str == nullptr)
  9. {
  10. return 0;
  11. }
  12. int position = 0;
  13. while (str[position] == ' ')
  14. {
  15. position++;
  16. }
  17. if (str[position] == '\0')
  18. {
  19. return 0;
  20. }
  21. int signal = 1;
  22. if (str[position] == '+' || str[position] == '-')
  23. {
  24. if (str[position] == '-')
  25. {
  26. signal = -1;
  27. }
  28. position++;
  29. }
  30. long long result = 0;// 注意这里是long long
  31. while (str[position] >= '0' && str[position] <= '9')
  32. {
  33. result = result * 10 + str[position] - '0';
  34. if (result * signal > INT_MAX)
  35. {
  36. return INT_MAX;
  37. }
  38. if (result * signal < INT_MIN)
  39. {
  40. return INT_MIN;
  41. }
  42. position++;
  43. }
  44. return result * signal;
  45. }
  46. };

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读