当前位置:网站首页>87. Convert String to Integer
87. Convert String to Integer
2022-07-31 00:58:00 【Hunter_Kevin】
题目
请你写一个函数 StrToInt,实现把字符串转换成整数这个功能.
当然,不能使用 atoi 或者其他类似的库函数.
数据范围
输入字符串长度 [0,20].
样例
输入:“123”
输出:123
注意:
你的函数应满足下列条件:
忽略所有行首空格,找到第一个非空格字符,可以是 ‘+/−’ 表示是正数或者负数,紧随其后找到最长的一串连续数字,将其解析成一个整数;
整数后可能有任意非数字字符,请将其忽略;
如果整数长度为 0,则返回 0;
如果整数大于 INT_MAX(231−1),请返回 INT_MAX;如果整数小于INT_MIN(−231) ,请返回 INT_MIN;
代码
class Solution {
public:
int strToInt(string str) {
long long res = 0;//Possibly a long integer,超过int
bool isPos = true;//Assume a positive number
for(int i = 0; str[i]; i++){
//遍历字符串
if(str[i] == ' ' || str[i] == '+')continue;//If it is a space or a positive sign,则跳过
if(str[i] == '-'){
//如果是负号,is marked as a negative number,并跳过
isPos = false;
continue;
}
if(str[i] < '0' || str[i] > '9')break;//If a non-numeric character is traversed,则结束遍历
res = res * 10 + str[i] - '0';//Accumulate numbers and
if(isPos && res > INT_MAX) return INT_MAX;//如果是正数,并且long long The cumulative sum of types has exceeded2^31-1,exceeds the maximum positive value
if(!isPos && res - 1 > INT_MAX) return INT_MIN;//如果是负数,并且long long The cumulative sum of types has exceeded2^31,The negative maximum value is exceeded
}
//Put the judgment on whether it is out of rangeforThe purpose of the loop is,Prevent numbers from exceedinglonglong,Accumulate and data overflow
if(!isPos)res *= -1;//如果是负数,则变号
return res;
}
};
边栏推荐
猜你喜欢
随机推荐
typescript9 - common base types
822. 走方格
MySQL高级-六索引优化
C language force buckles the rotating image of the 48th question.auxiliary array
Go study notes (84) - Go project directory structure
typescript10-commonly used basic types
ELK部署脚本---亲测可用
typescript12 - union types
【Multithreading】
typescript16-void
MySQL database constraints, table design
VS warning LNK4099:未找到 PDB 的解决方案
Filter (Filter)
解析云原生消息流系统 Apache Pulsar 能力及场景
xss bypass: prompt(1)
Mysql:Invalid default value for TIMESTAMP
A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
typescript16-void
typescript11-数据类型
ShardingSphere's public table combat (7)