Leetcode之string To Integer (atoi) 字符串转化为整形
String to Integer
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
解法:这题的测试数据很强包含了各种情况,主要注意两点:
- 遇到非数字字符,结束,返回之前的数值。
- 越界处理,许多人用long保存,然后直接处理越界情况,但long的存储范围也有限制,如
222147483648222222222222222222222222222222222222222222222
这个数据就过不了。(用long long
应该还是可以,因为在某次循环中肯定会超过MAXINT
,但如果题目是要求对字符串转化为long
,那就没有办法了)这里对越界使用现乘以10再除以10的比较方法,如果乘10除10后数字没有发生变化,则没有越界。
代码如下:
//{java}
public class Solution {
public int atoi(String str) {
int max = 2147483647;
int min = -2147483648;
int k=0,i=0;
boolean isPositive = true;
str=str.trim();
if(str.length()==0)
return 0;
if(str.charAt(0)=='-')
{
isPositive = false;
i++;
}else if(str.charAt(0)=='+')
{
i++;
}
for(;i<str.length();i++)
{
char c = str.charAt(i);
if(c>'9'|c<'0')
break;
int t=k;
k*=10;
k+=str.charAt(i)-'0';
if(k/10!=t)
{
if(isPositive)
return max;
else
return min;
}
}
if(!isPositive)
k*=-1;
return k;
}
}
blog comments powered by Disqus