题目
题解
思路倒是不难,细节太多了…第一道交了这么多遍还不过的题,真的给我做吐了…难怪这题通过率只有21.7%
注意:字符串转整型公式 r e s = r e s ∗ 10 + r res=res*10+r res=res∗10+r,如果用这个公式就不需要去掉前导0,省掉了很多不必要的判断
class Solution {
public int myAtoi(String s) {
//丢弃前导空格
s=s.trim();//去掉首尾空格
int n=s.length();
if(n==0)
return 0;
//正负号
long res=0;
int i=0,flag=1;
char symbol=s.charAt(i);
if(symbol=='+'||symbol=='-'){
flag=symbol=='+'?1:-1;
i++;
}
else if(!Character.isDigit(symbol))
return 0;
//字符串数字转int数字
for(;i<n && Character.isDigit(s.charAt(i));i++){
res=res*10+(s.charAt(i)-'0');
if(res*flag<Integer.MIN_VALUE) return Integer.MIN_VALUE;
if(res*flag>Integer.MAX_VALUE) return Integer.MAX_VALUE;
}
return (int)res*flag;
}
}
附错过的边界值:
" -42"
"words and 987"
"-91283472332"
"+-12"
"2147483646"
"-2147483648"
" 0000000000012345678"
"00000-42a1234"
"3.14159"
"-000000000000001"
" 0000000000000 "
" -0012a42"
"0 123"
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459"
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)