JZ49-把字符串转换成整数
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
class Solution2 {
public int StrToInt(String str) {
if (str == null || str.length() == 0) {
return 0;
}
boolean isNegative = str.charAt(0) == '-';
int ret = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i == 0 && (c == '+' || c == '-')) { //如果首位是+-,直接下一个数字
continue;
}
if (c < '0' || c > '9') {
return 0;
}
ret = ret * 10 + (c - '0');
}
return isNegative ? -ret : ret;
}
}
查看8道真题和解析