2019-11-02 12:07:41 +08:00
|
|
|
|
# 67. 把字符串转换成整数
|
|
|
|
|
|
2019-11-03 23:57:08 +08:00
|
|
|
|
## 题目链接
|
|
|
|
|
|
2019-11-02 12:07:41 +08:00
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。
|
|
|
|
|
|
|
|
|
|
```html
|
|
|
|
|
Iuput:
|
|
|
|
|
+2147483647
|
|
|
|
|
1a33
|
|
|
|
|
|
|
|
|
|
Output:
|
|
|
|
|
2147483647
|
|
|
|
|
0
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public int StrToInt(String str) {
|
2020-02-20 11:59:31 +08:00
|
|
|
|
if (str == null)
|
2019-11-02 12:07:41 +08:00
|
|
|
|
return 0;
|
2020-02-20 11:59:31 +08:00
|
|
|
|
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;
|
2019-11-02 12:07:41 +08:00
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|