题意
//在数字前出现空格,略过。 “ 123” 返回123
//正负号只能有一个。+-123 返回0
//正负号后紧跟数字。+ 123 返回0
//在数字后出现非数字字符,扔掉该非数字字符及其后续字符。123f34 返回123
//若超过最大INT或小于最小INT,返回最大INT或最小INT。
C++
class Solution {
public:
int myAtoi(string str) {
if(str.length() == 0)
{
return 0;
}
bool negative = false;
int indexInStr = 0;
double result = 0;
bool noSymbol = true;
while(indexInStr < str.length())
{
if(str[indexInStr] <= '9' && str[indexInStr] >= '0')
{
break;
}
else
{
if(str[indexInStr] == ' ')
{
if(!noSymbol)
{
return 0;
}
}
else if(str[indexInStr] == '-')
{
if(!noSymbol)
{
return 0;
}
negative = true;
noSymbol = false;
}
else if(str[indexInStr] == '+')
{
if(!noSymbol)
{
return 0;
}
negative = false;
noSymbol = false;
}
else
{
return 0;
}
}
++indexInStr;
}
while(indexInStr < str.length())
{
if(str[indexInStr] > '9' || str[indexInStr] < '0')
{
break;
}
result = result * 10 + str[indexInStr] - '0';
if(!negative && result > INT_MAX)
{
return INT_MAX;
}
++indexInStr;
}
if(negative)
{
result = 0 - result;
if(result < INT_MIN)
{
return INT_MIN;
}
}
return result;
}
};
JAVA
方法一
47ms
public int myAtoi(String str) {
long result = 0;
boolean negative = false;
char ch;
int index = 0;
for(;index < str.length(); ++index){
ch = str.charAt(index);
if(ch =='-'){
negative = true;
++index;
break;
}else if(ch =='+'){
++index;
break;
}else if('0' <= ch && ch <= '9'){
break;
}else if(ch != ' '){
return 0;
}
}
for(;index < str.length(); ++index){
ch = str.charAt(index);
if ('0' <= ch && ch <= '9'){
if (negative){
result = result * 10 - (ch - '0');
}else{
result = ch - '0' + result * 10;
}
if(result < Integer.MIN_VALUE){
result = Integer.MIN_VALUE;
break;
}else if(result > Integer.MAX_VALUE){
result = Integer.MAX_VALUE;
break;
}
}else{
break;
}
}
return (int)result;
}