⭐️ 题目描述

🌟 O链接 https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&&tqId=11202&rp=6&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking
思路: 首先需要检查第一位是否有符号位,如果有符号位那么转换整数就是从下标为 1 开始,没有符号位就是从下标为 0 开始,当然也需要有一个变量来记录正负号。在转换中若遇到非数字字符则直接 return,转换的时候还要考虑溢出的情况,需要使用一个精度比 int 高的类型来判断当前的值是否超出 int 的精度,因为 int 类型肯定不会超出 int 的精度,而 int 的最大值和最小值在库里有这样两个宏代表 INT_MAX INT_MIN,从高位依次转换 ans = ans * 10 + (str[is_symbol] - '0')。
ps: "123" => { ans = 0 * 10 + 1 } -> { ans = 1 * 10 + 2 } -> {ans = 12 * 10+ 3} -> { ans = 123 }
代码:
class Solution {
public:
int StrToInt(string str) {
// 检查第一位是否是符号位
int is_symbol = 0; // 是否有符号位
int mark = 1; // 默认正数
if (str[0] == '+') {
is_symbol = 1;
} else if (str[0] == '-') {
is_symbol = 1;
mark = -1;
}
long long ans = 0;
while (is_symbol < str.size()) {
if (!isdigit(str[is_symbol])) { // 不是数字字符直接结束
return 0;
}
ans = ans * 10 + (str[is_symbol] - '0');
if (ans > INT_MAX || ans < INT_MIN) { // 大于整型最大值或者小于整型最大值直接结束
return 0;
}
is_symbol++;
}
return (int)ans * mark;
}
};



















