在做leetcode8, 一道string转成int的问题时,遇到了这个问题。
我的代码如下,因为是要讲string转换成int, 所以我就使用long型先储存了结果,再最后return (int) result.
基本功能都能实现,然而在提交代码时,系统如果输入一个大于long型最大值的数,如"+9223372036854775808",输出结果就是0,"+9223372036854775809"为1。 然而我在代码中的描述是,如果大于int型的最大值,统一输出int型的最大值,但当输入为一个大于long型数的数值时,判断语句就失效了。
求问,如何实现这段代码?用什么类型的数据存放呢?
另外,为何大于long型的数值会从0,1……开始重新排列一遍呢?
代码如下:
public class Solution {
public int myAtoi(String str) {
long result = 0;
if(str == null || str.length()<=0)
return 0;
String newstr = str.trim();
if(newstr.charAt(0) =='+'){
for(int i=1;i
if (Character.isDigit(newstr.charAt(i)))
result = result*10 + (newstr.charAt(i) - '0');
else
break;
}
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)result;
}
else if (newstr.charAt(0) == '-'){
for(int i=1;i
if (Character.isDigit(newstr.charAt(i)))
result = result*10 + (newstr.charAt(i) - '0');
else
break;
}
result = result*-1;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
else
return (int)result;
}
else if (Character.isDigit(newstr.charAt(0))){
for(int i=0;i
if (Character.isDigit(newstr.charAt(i)))
result = result*10 + (newstr.charAt(i) - '0');
else
break;
}
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)result;
}
else
return 0;
}
}