当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

Rocky/GNU之Zabbix部署(1)

Jmeter参数传递方式(token传递,接口关联等)

The client series of the DOM series

论文理解:“Designing and training of a dual CNN for image denoising“

typescript14-(单独指定参数和返回值的类型)

Thesis understanding: "Designing and training of a dual CNN for image denoising"

MySQL数据库面试题总结(2022最新版)

Regular expression password policy and regular backtracking mechanism bypass

这个项目太有极客范儿了

typescript13 - type aliases
随机推荐
网站频繁出现mysql等数据库连接失败等信息解决办法
mysql索引失效的常见9种原因详解
Typescript14 - (type) of the specified parameters and return values alone
typescript17-函数可选参数
Unity2D horizontal version game tutorial 4 - item collection and physical materials
【Multithreading】
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]
WMware Tools installation failed segmentation fault solution
Asser uses ant sword to log in
Error occurred while trying to proxy request The project suddenly can't get up
一万了解 Gateway 知识点
MySQL master-slave replication and read-write separation script - pro test available
Rocky/GNU之Zabbix部署(1)
Preparations for web vulnerabilities
Image processing tool design
Regular expression password policy and regular backtracking mechanism bypass
Adding, deleting, modifying and checking the foundation of MySQL
Zabbix干啥用?