题解 | 把字符串转换成整数(atoi)
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int StrToInt (String s) {
// write code here
if (s == null || s.length() == 0) return 0;
int index = 0;
int n = s.length();
int sign = 1;//是正数还是负数,默认是正数
int res = 0;//存放结果
//1.跳过空格
while (index < n && s.charAt(index) == ' ') {
index ++;
}
if (index == n ) return 0; //如果全是空格,直接返回0
//处理正负号
char charFirst = s.charAt(index);
if (charFirst == '+') {
sign = 1;
index++;
}
if (charFirst == '-') {
sign = -1;
index++;
}
//设置边界值,用来防溢出
int boundary = Integer.MAX_VALUE / 10;
//组装数字
while (index < n) {
char c = s.charAt(index);
// 如果遇到非数字字符,直接结束提取
if (c < '0' || c > '9') {
break;
}
// 将字符转换为实际的整型数字
int digit = c - '0';
// 溢出拦截
// 如果当前的 res 已经大于 boundary,那下一步 res * 10 必定溢出。
// 如果 res 等于 boundary,那下一步加上 digit 后,digit 不能超过 7 (因为 MAX_VALUE 尾数是 7)。
if (res > boundary || (res == boundary && digit > 7)) {
// 根据符号决定返回最大正数还是最小负数
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
// 组装数字
res = res * 10 + digit;
index++;
}
// 返回带符号的最终结果
return res * sign;
}
}