解题思路
1.寻找非空字符。如果查找失败,返回0。
2.判断第一个非空字符是否为正负号。如果是则偏移一位
3.pos当前字符是否为数字,如果是则返回0
4.查找最后一个非数字字符。
5.计算数值
6.如果溢出,按照当前正负号标志赋值最大、最小值。否则按正常途径处理
class Solution {
public:
int myAtoi(string str) {
int pos = 0;
while (pos<str.length()&&str.at(pos) == ' ')pos++;
if (pos == str.length())return 0;
bool bMinus = false;
if ('-' == str.at(pos) || '+' == str.at(pos))
{
bMinus = '-' == str.at(pos)?true:false;
pos++;
}
int critical = pos;
if (pos >= str.length()||str.at(pos) < '0'||str.at(pos) > '9')
return 0;
while (pos < str.length() && str.at(pos) >= '0'&&str.at(pos) <= '9')
{
pos++;
}
int i = pos-1;
int k = 0;
int add = 0;
while (i >= critical)
{
add += (str.at(i) - '0')*pow(10,k);
if (add < 0)
{
add = bMinus ? INT_MIN : INT_MAX;
return add;
}
i--;
k++;
}
add = bMinus ? add*-1 : add;
return add;
}
};
作者:ji-fan-feng-yu
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-ji-fan-fe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
作者:ji-fan-feng-yu
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-ji-fan-fe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。