【题目描述】
Implement atoi to convert a string to an integer.
【思路】
这道题目要求很简单,就是将字符串转换为整型数,难点在于要全面考虑字符串可能出现的情况:
1.字符串中可能会出现空格(用isspace()函数解决)
2.字符串中会出现正负符号(要事先加以判断并用flag加以标示)
3.可能会出现不止一个符号(非数字)出现的情况(这种情况应视为结果为0)‘
【代码】
class Solution {
public:
int myAtoi(string str) {
long result=0;
int len=str.size();
long flag=1;
int pos=0;
while(isspace(str[pos])) pos++;
if(str[pos]=='+') pos++;
else if(str[pos]=='-'){
pos++;
flag=-1;
}
while(str[pos]<='9'&&str[pos]>='0'){
result=result*10+(str[pos]-'0');
if(flag*result>INT_MAX) return INT_MAX;
if(flag*result<INT_MIN) return INT_MIN;
pos++;
}
return result*flag;
}
};