标签:com problems ems 情况 遍历 rto public amp ref
题目链接:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
应该先去除字符串首部的空格,然后再判断正负。
难点在于处理溢出。
INT_MAX 2147483647
INT_MIN -2147483648
class Solution {
public:
int strToInt(string str) {
long long number = 0;
bool is_minus = false;
int k = 0;
while (k < str.size() && str[k] == ‘ ‘) k ++ ;
if (str[k] == ‘+‘) k ++ ;
else if (str[k] == ‘-‘) is_minus = true, k ++ ;
while (k < str.size() && str[k] >= ‘0‘ && str[k] <= ‘9‘) {
number = number * 10 + str[k] - ‘0‘;
k ++ ;
}
if (is_minus) number *= -1;
if (number > INT_MAX) number = INT_MAX;
if (number < INT_MIN) number = INT_MIN;
return (int)number;
}
};
class Solution {
public:
int strToInt(string str) {
int number = 0;
//是否是负数
bool is_minus = false;
int k = 0;
//去除首部的空格
while (k < str.size() && str[k] == ‘ ‘) k ++ ;
//跳过符号位
if (str[k] == ‘+‘) k ++ ;
else if (str[k] == ‘-‘) is_minus = true, k ++ ;
//依次遍历每个字符 判断每个字符是不是数字0 - 9
while (k < str.size() && str[k] >= ‘0‘ && str[k] <= ‘9‘)
{
int x = str[k] - ‘0‘;
//判断是否越界
if(number > INT_MAX / 10 || (number == INT_MAX / 10 && x > INT_MAX % 10)) return is_minus ? INT_MIN : INT_MAX;
number = number * 10 + x;
k ++ ;
}
return is_minus ? -number : number;
}
};
标签:com problems ems 情况 遍历 rto public amp ref
原文地址:https://www.cnblogs.com/Trevo/p/12995382.html