版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/G_drive/article/details/89761622
问题描述
问题分析
分析题目,此题是数值处理的模拟题。处理逻辑稍微有点复杂,我真是被测试用例搞到自闭了…需要注意的地方有:
- 关于最大值、最小值的定义:
使用int INT_MIN = Integer.MIN_VALUE;
而不是int INT_MIN = -(int)Math.pow(2,31);
前者为-214783648,后者为-214783647。因为后者是用(int)Math.pow(2,31)
取负数,而(int)Math.pow(2,31)
是正数的最大值214783647,取负数就变成了-214783647,事实上,负数的最小值是-214783648。由于正数的三码合一,而导致正数的最大值是214783647而不是214783648。详细介绍参考:https://blog.csdn.net/claram/article/details/76682125 - 关于判定逻辑:
最大的限制条件是:依次扫描,只能遇到’ ’ 、’+’、’-‘以及数字字符,否则立即结束扫描,输出结果。
其次的限制条件是:一旦遇到了’+’、’-’,之后紧连着的字符只能是数字,否则立即结束扫描,输出结果。
再次就是:’ ‘很特殊,在没有遇到符号和数字之前,可以跳过;遇到了之后,’ '就作为结束符了。 - 令人崩溃的测试用例:
+:0
-:0
-:0
+1:1
+1:1
±2:0
+0 123:0- 0 123:0
20000000000000000000:2147483647
- 0 123:0
- 时间复杂度:O( n ),其中n = str.length()
- 空间复杂度:O( 1 }
Java代码
import java.math.BigInteger;
class Solution {
public int myAtoi(String str) {
int INT_MAX = Integer.MAX_VALUE;
int INT_MIN = Integer.MIN_VALUE;
if (str.length() == 0){return 0;}
int cur = 0;
boolean key = true; //false为已拿到符号
StringBuilder result_str = new StringBuilder();
while (cur < str.length()){
if (str.charAt(cur) == ' ' || str.charAt(cur) == '-' || str.charAt(cur) == '+' || (str.charAt(cur) >= 48 && str.charAt(cur) <= 57)){
//符合输入条件
if (!key){
//在已拿到符号的情况下
if (!(str.charAt(cur) >= 48 && str.charAt(cur) <= 57)){
//不是数字
break;
} else {
//是数字
result_str.append(str.charAt(cur));
}
} else {
//没拿到符号
if (str.charAt(cur) != ' '){
result_str.append(str.charAt(cur));
key = false;
}
}
cur++;
}else {break;}
}
if (result_str.length() == 0){return 0;}
try {
BigInteger result_big = new BigInteger(result_str.toString());
if (result_big.compareTo(BigInteger.valueOf(INT_MAX)) == 1){
return INT_MAX;
}
if (result_big.compareTo(BigInteger.valueOf(INT_MIN)) == -1){
return INT_MIN;
}
return result_big.intValue();
}catch (Exception e){
return 0;
}
}
}
结果分析
以上代码的执行结果:
执行时间 | 内存消耗 |
---|---|
18ms | 35.5MB |