LeetCode String to Integer (atoi)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1055. Shortest Way to Form String

Leetcode: String to Integer (atoi)

[leetcode]String to Integer (atoi)

leetcode8 String to Integer

Leetcode008. String to Integer (atoi)

LeetCode String to Integer (atoi)