首页 > 其他 > 详细

LeetCode String to Integer (atoi)

时间:2017-09-20 21:34:37      阅读:260      评论:0      收藏:0      [点我收藏+]

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.

需要考虑的情况很多:"-123";"124.123";"+-2";"+-";"     010";"2147483648";"9223372036854775809..."

具体代码:

public class StringToInt {
public static int myAtoi(String str) {
int flag=1;
double sum=0;
int index=0;
str=str.trim();
char[]s=str.toCharArray();
if(str==""){
return 0;
}
if(index<s.length&&(s[index]==‘-‘||s[index]==‘+‘)){
flag=s[index]==‘-‘?-1:1;
index++;
}
for(;index<s.length;index++){

if(s[index]<‘0‘||s[index]>‘9‘){
break;
}
sum=sum*10+s[index]-‘0‘;

}
sum = sum*flag>0?Math.min(sum*flag, Integer.MAX_VALUE):Math.max(sum*flag, Integer.MIN_VALUE);
return (int)sum;
}

}

LeetCode String to Integer (atoi)

原文:http://www.cnblogs.com/rain-bo/p/7563518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!