AcWing 87. 把字符串转换成整数 - Java
原题链接
中等
作者:
KYCygni
,
2021-03-31 13:15:58
,
所有人可见
,
阅读 230
Java 代码
class Solution {
public int strToInt(String str) {
long num = 0;
boolean neg = false;
//trim
String str1 = str.trim();
for (int i = 0; i < str1.length(); i ++)
{
if (str1.charAt(i) == '-' )
{
neg = true;
continue;
}
if (str1.charAt(i) == '+' )
continue;
if (!Character.isDigit(str1.charAt(i)))
break;
num = num * 10 + (long)(str1.charAt(i) - '0');
}
if (neg)
num *= -1;
if (num > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (num < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)num;
}
}