当前位置:网站首页>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;
}
};
边栏推荐
- ELK deployment script---pro test available
- MySQL master-slave replication and read-write separation script - pro test available
- Oracle has a weird temporary table space shortage problem
- How to Add a Navigation Menu on Your WordPress Site
- typescript9-常用基础类型
- This project is so geeky
- A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
- Can deep learning solve the parameters of a specific function?
- 网站频繁出现mysql等数据库连接失败等信息解决办法
- 什么是Promise?Promise的原理是什么?Promise怎么用?
猜你喜欢
随机推荐
ShardingSphere之读写分离(八)
Unity2D horizontal version game tutorial 4 - item collection and physical materials
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
background has no effect on child elements of float
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
Filter (Filter)
MySQL grant statements
论文理解:“Designing and training of a dual CNN for image denoising“
场景之多数据源查询及数据下载问题
[Yugong Series] July 2022 Go Teaching Course 015-Assignment Operators and Relational Operators of Operators
权限管理怎么做的?
WEB安全基础 - - -漏洞扫描器
Can deep learning solve the parameters of a specific function?
深度学习可以求解特定函数的参数么?
【多线程】
程序员工作三年攒多少钱合适?
【愚公系列】2022年07月 Go教学课程 019-循环结构之for
MySQL数据库面试题总结(2022最新版)
一万了解 Gateway 知识点
mysql索引失效的常见9种原因详解