[Leetcode] String to Integer (atoi)

太过爱你忘了你带给我的痛 2021-12-03 07:21 330阅读 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. 1 class Solution {
  2. 2 public:
  3. 3 int atoi(const char *str) {
  4. 4 assert(str != NULL);
  5. 5 while(isspace(*str)) str++; // remove ' '
  6. 6
  7. 7 int sign = (*str == '-') ? -1 : 1;
  8. 8 if (*str == '-' || *str == '+') // if can check one char
  9. 9 str++;
  10. 10
  11. 11 int ret = 0;
  12. 12 while(isdigit(*str)) // is digit
  13. 13 {
  14. 14 int digit = *str - '0';
  15. 15
  16. 16 if (INT_MAX / 10 >= ret)
  17. 17 ret *= 10;
  18. 18 else
  19. 19 return sign == -1 ? INT_MIN : INT_MAX;
  20. 20
  21. 21 if (INT_MAX - digit >= ret)
  22. 22 ret += digit;
  23. 23 else
  24. 24 return sign == -1 ? INT_MIN : INT_MAX;
  25. 25
  26. 26 str++;
  27. 27 }
  28. 28
  29. 29 return ret * sign;
  30. 30 }
  31. 31 };

转载于:https://www.cnblogs.com/easonliu/p/3631584.html

发表评论

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

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

相关阅读