LeetCode题解(8)--String to Integer (atoi)

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.

把字符串转化成整数,需要考虑全面(不看spoilers)。几种特殊情况:

1.有或者没有符号位。

2.先有很多空格。(这个有点坑,没想到)

3.字符串中出现非数字字符。(我直接认为输入错误return 0,但这道题是把它看做终止符)

4.转化的整数overflow。(存在long long里,然后看overflow没有。我overflow直接return 0,但这道题是截取最大能表达的数)

PS: 应该尝试用条件表达式简化代码。

自己的AC代码:

 1 class Solution {
 2 public:
 3     int myAtoi(string str) {
 4         long long x=0;
 5         int i,flag=1,begin=0,n=str.size();
 6         for(i=0;i<n;i++){
 7             if(str[i]!=' ')
 8                 break;
 9         }
10         begin=i;
11         if(str[begin]=='-'||str[begin]=='+'){
12             if(str[begin]=='-')
13                 flag=-1;
14             begin++;
15         } 
16         for(i=begin;i<n;i++){
17             if(isdigit(str[i])==1){
18                 x= 10*x+str[i]-'0';
19                 if(flag==1 && x>INT_MAX) 
20                     return INT_MAX;
21                 else if(flag==-1 && -x<INT_MIN)
22                     return INT_MIN;
23             }else
24                 break;
25         }
26         x=flag*x;
27         return x;
28     }
29 };
原文地址:https://www.cnblogs.com/aezero/p/4490694.html