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.
思路分析:public class Solution {
public int myAtoi(String str) {
//首先判断空值
if(str == null){
return 0;
}
//去掉空格的情况
str = str.trim();
if(str.length() == 0){
return 0;
}
int sign = 1;
int index = 0;
if(str.charAt(index) == '+'){
index++;
}else if(str.charAt(index) == '-'){
index++;
sign = -1;
}
//取得数字部分,遇到溢出和非数字退出
long number = 0;
for(;index < str.length();index++){
if(str.charAt(index) < '0' str.charAt(index) > '9'){
break;
}
number = number *10 + (str.charAt(index) - '0');
if(number >= Integer.MAX_VALUE){
break;
}
}
if(number * sign >= Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(number * sign <= Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return (int)number*sign;
}
}
2025 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123