当前位置:网站首页>87. 把字符串转换成整数
87. 把字符串转换成整数
2022-07-31 00:51: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;//有可能是长整型,超过int
bool isPos = true;//假设是正数
for(int i = 0; str[i]; i++){
//遍历字符串
if(str[i] == ' ' || str[i] == '+')continue;//如果是空格或者正号,则跳过
if(str[i] == '-'){
//如果是负号,则标记为负数,并跳过
isPos = false;
continue;
}
if(str[i] < '0' || str[i] > '9')break;//如果遍历到了非数字字符,则结束遍历
res = res * 10 + str[i] - '0';//累加数字和
if(isPos && res > INT_MAX) return INT_MAX;//如果是正数,并且long long 类型的累加和已经超过2^31-1,则超了正数最大值
if(!isPos && res - 1 > INT_MAX) return INT_MIN;//如果是负数,并且long long 类型的累加和已经超了2^31,则超了负数最大值
}
//把判断是否超范围放在for循环里面的目的是,防止数字超过longlong,累加和数据溢出
if(!isPos)res *= -1;//如果是负数,则变号
return res;
}
};
边栏推荐
- 人工智能与云安全
- 【愚公系列】2022年07月 Go教学课程 017-分支结构之IF
- The difference between h264 and h265 decoding
- XSS related knowledge
- MySQL高级-六索引优化
- Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
- Rocky/GNU之Zabbix部署(1)
- Adding, deleting, modifying and checking the foundation of MySQL
- MySQL的触发器
- typescript18-对象类型
猜你喜欢
随机推荐
typescript17 - function optional parameters
mysql索引失效的常见9种原因详解
unity2D横版游戏教程4-物品收集以及物理材质
typescript18-对象类型
【愚公系列】2022年07月 Go教学课程 015-运算符之赋值运算符和关系运算符
Unity2D horizontal version game tutorial 4 - item collection and physical materials
Thesis understanding: "Designing and training of a dual CNN for image denoising"
BOM系列之history对象
MySQL notes under
Consistency and Consensus of Distributed Systems (1) - Overview
DOM系列之 offset 系列
SereTOD2022 Track2 Code Analysis - Task-based Dialogue Systems Challenge for Semi-Supervised and Reinforcement Learning
Strict Mode for Databases
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
Common network status codes
typescript9 - common base types
BOM系列之Navigator对象
小程序-全局数据共享
场景之多数据源查询及数据下载问题
DOM系列之 client 系列









