Skip to content

Commit

Permalink
Merge pull request CyC2018#875 from yirenlee/master
Browse files Browse the repository at this point in the history
添加越界判断
  • Loading branch information
CyC2018 authored Feb 29, 2020
2 parents a4e84b4 + faa2ca6 commit 8f1da89
Showing 1 changed file with 45 additions and 12 deletions.
57 changes: 45 additions & 12 deletions notes/67. 把字符串转换成整数.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,53 @@ Output:

```java
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') /* 非法输入 */
if (str == null)
return 0;
ret = ret * 10 + (c - '0');
int result = 0;
boolean negative = false;//是否负数
int i = 0, len = str.length();
/**
* limit 默认初始化为*负的*最大正整数 ,假如字符串表示的是正数
* 由于int的范围为-2147483648~2147483647
* 那么result(在返回之前一直是负数形式)就必须和这个最大正数的负数来比较来判断是否溢出,
*/
int limit = - Integer.MAX_VALUE;
int multmin;
int digit;

if (len > 0) {
char firstChar = str.charAt(0);//首先看第一位
if (firstChar < '0') { // 有可能是 "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;//在负号的情况下,判断溢出的值就变成了 整数的 最小负数了
} else if (firstChar != '+')//第一位不是数字和-只能是+
return 0;
if (len == 1) // Cannot have lone "+" or "-"
return 0;
i++;
}
multmin = limit / 10;
while (i < len) {
digit = str.charAt(i++)-'0';
if (digit < 0 || digit > 9)
return 0;
//判断溢出
if (result < multmin) {
return 0;
}
result *= 10;
if (result < limit + digit) {
return 0;
}
result -= digit;
}
} else {
return 0;
}
//如果是正数就返回-result(result一直是负数)
return negative ? result : -result;
}
return isNegative ? -ret : ret;
}
```


Expand Down

0 comments on commit 8f1da89

Please sign in to comment.