LeetCode: String to Integer (atoi)

这种题就是考你考虑了多少些情况,第一次没有考虑到的情况有:+-号,超出int范围,多数次过

 1 class Solution {

 2 public:

 3     int atoi(const char *str) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         bool showed = false;

 7         int s = 0;

 8         bool negtive = false;

 9         for (int i = 0; *(str+i) != '\0'; i++) {

10             if (!showed) {

11                 if (*(str+i) == ' ') continue;

12                 if (*(str+i) >= '0' && *(str+i) <= '9') {

13                     showed = true;

14                     s = (int)(*(str+i) - '0');

15                 }

16                 else if (*(str+i) == '-') {

17                     showed = true;

18                     negtive = true;

19                 }

20                 else if (*(str+i) == '+') showed = true;

21                 else return 0;

22             }

23             else {

24                 if (*(str+i) == ' ') return negtive? -s : s;

25                 if (*(str+i) >= '0' && *(str+i) <= '9') {

26                     if (s > (INT_MAX - (int)(*(str+i)-'0'))/10)

27                         return negtive? INT_MIN : INT_MAX;

28                     s = s*10 + (int)(*(str+i) - '0');

29                 }

30                 else return negtive? -s : s;

31             }

32         }

33         return negtive? -s : s;

34     }

35 };

 后来写了个更加精简的代码

 1 class Solution {

 2 public:

 3     int atoi(const char *str) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         while (isspace(*str)) str++;

 7         int ret = 0;

 8         bool isNeg = false;

 9         if (*str == '+') str++;

10         if (*str == '-') {

11             isNeg = !isNeg;

12             str++;

13         }

14         while (isdigit(*str)) {

15             if (ret > (INT_MAX - int(*str-'0'))/10) return isNeg? INT_MIN : INT_MAX;

16             ret = ret*10+int(*str-'0');

17             str++;

18         }

19         return isNeg? -ret : ret;

20     }

21 };

 

 

你可能感兴趣的:(LeetCode)