1 回答
TA贡献1806条经验 获得超5个赞
for (int i = 0; i < newstr.length(); i++)
应该改成for (int i = 1; i < newstr.length(); i++)
, 因为按照你的描述,下标为0的字符应该是+
或者-
。
public class Solution {
public int atoi(String str) {
if (str == null || str.length() <= 0)
return 0;
long rs = 0;
char[] chArr = str.trim().toCharArray();
boolean isPositive = chArr[0] == '+' || Character.isDigit(chArr[0]);
int start = Character.isDigit(chArr[0]) ? 0 : 1;
for (; start < chArr.length; start++) {
if (Character.isDigit(chArr[start]))
rs = rs * 10 + (chArr[start] - '0');
}
rs = isPositive ? rs : -rs;
if (isPositive)
return rs > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rs;
else
return rs < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) rs;
}
public static void main(String[] args) {
System.out.println(new Solution().atoi("-1100"));
}
}
添加回答
举报