本题的题型内容如下:
本题的解决思路主要注意一下几点:
1,当输入为空时的处理;
2,前面的空白字符的处理
3,如何得到前面的正负号
4,注意最大值和最小值,防止溢出
算法实现
java
class Solution {
public int myAtoi(String str) {
int index = 0;
int total = 0;
int sign = 1;
// Check if empty string
if(str.length() == 0)
return 0;
// remove white spaces from the string
while(index < str.length() && str.charAt(index) == ' ')
index++;
if (index == str.length()) return 0;
// get the sign
if(str.charAt(index) == '+' || str.charAt(index) == '-') {
sign = str.charAt(index) == '+' ? 1 : -1;
index++;
}
// convert to the actual number and make sure it's not overflow
while(index < str.length()) {
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) break;
// check for overflow
if(Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = total*10 + digit;
index++; // don't forget to increment the counter
}
return total*sign;
}
}
python:
class Solution:
def myAtoi(self,str):
"""
:type str:str
:rtype int
"""
str=str.strip()
number=""
for x in str:
if x.isalpha() and number =="":
return 0
elif x.isalpha():
break
elif x==".":
break
elif x==" ":
break
elif(x=="+" or x=="-") and number=="":
number=number+x
elif(x=="+" or x=="-") and number!="":
break
elif (x=="+" or x=='-') and (number[-1]=="+" or number[-1]=="-"):
return 0
elif (x=="+" or x=="-") and ("+" in number or "-"in number):
break
elif x.isdigit():
number=number+x
if number ==""or number =="+" or number =="-":
return 0
else:
if int(number)>((2**31)-1):
return (2**31)-1
elif int(number)<-(2**31):
return -(2**31)
else:
return int(number)