当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
Preparations for web vulnerabilities
Error occurred while trying to proxy request The project suddenly can't get up
MySQL高级-六索引优化
xss bypass: prompt(1)
论文理解:“Designing and training of a dual CNN for image denoising“
【多线程】
This project is so geeky
基于Keras_bert模型的Bert使用与字词预测
Typescript14 - (type) of the specified parameters and return values alone
[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]
随机推荐
typescript15- (specify both parameter and return value types)
ShardingSphere's public table combat (7)
SereTOD2022 Track2 Code Analysis - Task-based Dialogue Systems Challenge for Semi-Supervised and Reinforcement Learning
ShardingSphere read-write separation (8)
Basic usage of async functions and await expressions in ES6
【愚公系列】2022年07月 Go教学课程 013-常量、指针
Typescript18 - object type
tensorflow与GPU版本对应安装问题
WEB Security Basics - - - Vulnerability Scanner
The client series of the DOM series
API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试
小黑leetcode之旅:104. 二叉树的最大深度
A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
What is Promise?What is the principle of Promise?How to use Promises?
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
typescript14-(单独指定参数和返回值的类型)
The difference between h264 and h265 decoding
【Yugong Series】July 2022 Go Teaching Course 019-For Circular Structure
MySQL高级-六索引优化
SWM32 Series Tutorial 6 - Systick and PWM