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.
这道题目是比较简单的字符串操作题目,但是题目中的坑还是挺多的,不认真做的话很难Accept ,下面贴代码:因为性能分析中运算时间达到了61ms,所以我的代码只适合给新手提供参考,如何提高性能还需要进一步的思考和修改。
class Solution {
public int myAtoi(String str) {
//先去前后空格,题目中前后有空格也算是有效格式
str = str.trim();
String origin = str;
if(str.isEmpty()){
return 0;
}
//用StringBuilder来存储字符
StringBuilder strbuff = new StringBuilder();
//去掉正负号
if(str.startsWith("-")||str.startsWith("+")){
str=str.substring(1);
System.out.println(str);
}
int temp =0;
//获取数字,遇到非数字则终止
for(int i=0;i<str.length();i++){
temp = (int)str.charAt(i);
if(temp>=48&&temp<=57){
strbuff.append(str.charAt(i));
}else{
break;
}
}
if(strbuff.length()==0){
return 0;
}
int result = 0;
使用parseint进行解析,如果超出int值范围则返回Int 的最大值
try{
result = Integer.parseInt(strbuff.toString());
}catch(Exception e){
if(origin.startsWith("-")){
return -2147483648;
}else{
return 2147483647;
}
}
//判断正负
if(origin.startsWith("-")){
return 0-result;
}
return result;
}
}