8.jpeg

    代码 :

    1. class Solution {
    2. public:
    3. int myAtoi(string str) {
    4. // trim all leading 0;
    5. int l = 0;
    6. while(l < str.size() && str[l] == ' ') {
    7. l ++;
    8. }
    9. if(l == str.size()) {
    10. return 0;
    11. }
    12. // check the sign
    13. int sign = 1;
    14. if (str[l] == '-') {
    15. sign = -1;
    16. l ++ ;
    17. }
    18. else if (str[l] == '+') {
    19. sign = 1;
    20. l ++ ;
    21. }
    22. // parse the integer
    23. int res = 0;
    24. while(l < str.size() && isdigit(str[l])) {
    25. int digit = str[l] - '0';
    26. // res * 10 + digit > INT_MAX
    27. if(sign == 1 && (res > (INT_MAX - digit) / 10) ) {
    28. return INT_MAX;
    29. }
    30. // -res * 10 - digit < INT_MIN
    31. else if (sign == -1 && (-res < (INT_MIN + digit) / 10) ) {
    32. return INT_MIN;
    33. }
    34. // [-2^31, 2^31 - 1]
    35. if( -res * 10 - digit == INT_MIN)
    36. return INT_MIN;
    37. res = res * 10 + digit;
    38. l ++ ;
    39. }
    40. res *= sign;
    41. return res;
    42. }
    43. };
    1. class Solution {
    2. public:
    3. int myAtoi(string s) {
    4. /* skip all leading space */
    5. int l = 0;
    6. while(l < s.size() && s[l] == ' ')
    7. l ++;
    8. if(l == s.size()) return 0;
    9. /* check the sign of int */
    10. int sign = 1;
    11. if(s[l] == '-') sign = -1, l ++;
    12. else if (s[l] == '+') l ++;
    13. long long res = 0;
    14. while(l < s.size() && isdigit(s[l])) {
    15. res = res * 10 + s[l] - '0';
    16. l ++ ;
    17. if(res > INT_MAX) break;
    18. }
    19. res *= sign;
    20. if(res > INT_MAX) return INT_MAX;
    21. if(res < INT_MIN) return INT_MIN;
    22. return res;
    23. }
    24. };