当前位置:网站首页>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;
}
};
边栏推荐
- typescript11 - data types
- 【愚公系列】2022年07月 Go教学课程 017-分支结构之IF
- background has no effect on child elements of float
- ShardingSphere之垂直分库分表实战(五)
- 网站频繁出现mysql等数据库连接失败等信息解决办法
- unity2D横版游戏教程4-物品收集以及物理材质
- 【ABAP】MFBF过账到质量检验库存类型Demo
- Basic usage of async functions and await expressions in ES6
- typescript16-void
- Strict Mode for Databases
猜你喜欢
Mini Program - Global Data Sharing
typescript17-函数可选参数
Preparations for web vulnerabilities
Meeting OA project pending meeting, all meeting functions
【多线程】
Problem record in the use of TypeScript
ShardingSphere之未分片表配置实战(六)
ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!
How to Add a Navigation Menu on Your WordPress Site
Shell programming of conditional statements
随机推荐
分布式系统的一致性与共识(1)-综述
ShardingSphere's vertical sub-database sub-table actual combat (5)
MySQL grant statements
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
mysql索引失效的常见9种原因详解
MySQL数据库面试题总结(2022最新版)
ROS2系列知识(3):环境配置
go mode tidy出现报错go warning “all“ matched no packages
The difference between h264 and h265 decoding
Understand from the 11 common examples of judging equality of packaging types in the written test: packaging types, the principle of automatic boxing and unboxing, the timing of boxing and unboxing, a
Shell编程之条件语句
ShardingSphere之读写分离(八)
SWM32 Series Tutorial 6 - Systick and PWM
ShardingSphere's public table combat (7)
ELK deployment script---pro test available
Meeting OA project pending meeting, all meeting functions
Error occurred while trying to proxy request项目突然起不来了
ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!
unity2D横版游戏教程4-物品收集以及物理材质
typescript18-对象类型