第49题 把字符串转换成整数
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
class Solution {
public:
int StrToInt(string str) {
const int length = str.length();
int isNegtive = 1, overValue = 0;
int digit = 0, value = 0;
if (length == 0) return 0;
else {
int idx = 0;
if (str[0] == '-') { isNegtive = -1; idx = 1;}
else if (str[0] == '+') {idx = 1;}
for (; idx<length; idx++) {
digit = str[idx]-'0';
// overValue表示本轮循环是否会越界
overValue = isNegtive*value - INT_MAX/10
+ (((isNegtive+1)/2 + digit > 8) ? 1:0);
if (digit<0 || digit>9) return 0;
else if (overValue > 0) return 0;
value = value*10 + isNegtive*digit;
}
return value;
}
}
};
class Solution:
def strToInt(self, str: str) -> int:
str = str.strip()
if not str:
return 0
int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
res, i, sign = 0, 1, 1
if str[0] == '-':
sign = -1
elif str[0] != '+':
i = 0
for c in str[i:]:
if not '0' <= c <= '9' : break
if res > bndry or res == bndry and c > '7':
return int_max if sign == 1 else int_min
res *= 10
res += ord(c) - ord('0')
return sign * res
思路:
数值越界,即大于 2147483647,或小于 -2147483648,通过观察程序结构,我们发现,每次循环时 value 的值都会扩大10倍(乘以10),那么,我们是否就可以利用 INT_MAX/10 的值来提前一步判断是否会越界呢?这里我们以正数的越界为例进行解释:
- 当 value > INT_MAX/10 时,说明本轮扩大10倍后,value 必将越界(超过 INT_MAX);
- 当 value == INT_MAX/10 时,说明扩大10倍后,value 可能越界,也可能不越界,需要利用当前的加数 digit 来进行进一步的判断:当 digit > 7 时(以正数为例),越界;
- 否则,当 value < INT_MAX/10 时,本轮循环必不越界(扩大10倍后也小于 INT_MAX);
该博客主要讨论如何在不允许使用内置字符串转整数库函数的情况下,实现将字符串转换为整数的功能。文章中提供了两种不同的C++和Python实现方式,并详细解释了代码逻辑,特别是如何通过防止数值越界来确保计算的正确性。核心思想是利用每次乘以10后可能的越界条件来提前判断,并在循环中检查字符是否为有效数字。
172万+

被折叠的 条评论
为什么被折叠?



