码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode String to Integer (atoi)

时间:2017-09-20 22:05:12      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:UI   oss   很多   rar   ide   wan   nbsp   imp   static   

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)

标签:UI   oss   很多   rar   ide   wan   nbsp   imp   static   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!