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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
Subscribe to see which companies asked this question.
题目的意思是给出参数String类型 转化为int类型的。-123gs345
结果是-123 ,同时要考虑边界值,此题很简单,但是想要写对却不是那么容易,解题的思路自然是循环字符串,字符串可以以“-”“+”开头,代表正负数,用一个变量存起来这个数是正还是负,对字符串进行截取之后的结果可以循环,如果某一个字符是数字,则之前的结果*10 加上这个数字,如果字符不是数字则直接返回,但是要注意几点:
1,注意边界值的验证。
2,注意判断不要造成溢出。
Java代码:
public static int myAtoi(String str) {
if(str==null||"".equals(str.trim()))
return 0;
Long result=(long) 0;
str=str.trim();
boolean flag=false;
if(str.startsWith("+")||str.startsWith("-")){
if(str.startsWith("-")){
flag=true;
}
str=str.substring(1, str.length());
}
for(int i=0;i<str.length();i++){
char strTemp=str.charAt(i);
if("0123456789".contains(String.valueOf(strTemp))){
if("0123456789".contains(String.valueOf(strTemp))){
if(flag){
result = result*10-Integer.parseInt(String.valueOf(strTemp));
if(Integer.MIN_VALUE>result){
return Integer.MIN_VALUE;
}
}else{
result = result*10+Integer.parseInt(String.valueOf(strTemp));
if(Integer.MAX_VALUE<result){
return Integer.MAX_VALUE;
}
}
}else{
return result.intValue();
}
}else{
return result.intValue();
}
}
return result.intValue();
}