当前位置:网站首页>牛客刷题——把字符串转换成整数
牛客刷题——把字符串转换成整数
2022-06-11 18:14:00 【HHYX.】
题目链接:把字符串转换成整数
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为 0 或者字符串不是一个合法的数值则返回 0
数据范围:字符串长度满足 0 \le n \le 100 \0≤n≤100
进阶:空间复杂度 O(1) \O(1) ,时间复杂度 O(n) \O(n)
注意:
①字符串中可能出现任意符号,出现除 +/- 以外符号时直接输出 0
②字符串中可能出现 +/- 且仅可能出现在字符串首位。
输入描述:
输入一个字符串,包括数字字母符号,可以为空
返回值描述:
如果是合法的数值表达则返回该数字,否则返回0
题目分析
题中要求将字符串转换为整数,不能使用库函数等。其中如果字符串包含非法字符则返回0.实现这个转换可以先对符号进行判断其正负,正负号只能出现在第一个字符上,因此可以先进行判断。如果没有正负号则直接进行字符串转换。使用循环遍历字符串,依次将字符转换为数字只需要将数字字符减去字符0即可,再进行求和即可。求和公式为sum=sum*10+(str[i]-‘0’),这样就可以求出总和,最后根据正负来进行计算即可。代码实现如下:
代码实现
int StrToInt(string str) {
int i = 0;
int sum = 0;//返回值 整数大小
int flag = 1;//正负判断依据 1代表正 0代表负
for (i = 0; i < str.size(); i++)
{
if (i != 0 && (str[i] < '0' || str[i]>'9'))//出现非法字符情况
{
return 0;
}
else
{
if (i == 0)
{
if (str[i] == '+')
{
flag = 1;
continue;
}
else if (str[i] == '-')
{
flag = 0;
continue;
}
else
{
sum = sum * 10 + (str[i] - '0');
continue;
}
}
sum = sum * 10 + (str[i] - '0');
}
}
if (flag == 0)
{
sum *= -1;
}
return sum;
}

边栏推荐
- 力扣23题,合并K个升序链表
- SA token single sign on SSO mode 2 URL redirection propagation session example
- ctfhub-sql布尔盲注
- [c language] output the students with the highest scores with a structure. There can be multiple highest scores
- Reading summary of nacos2.x source code
- 力扣32题最长有效括号
- 网络和并发编程常见面试题
- LDPC 7 - 解码简单例子
- 5 minutes to understand the red, blue and purple in the attack and defense drill
- 【无标题】
猜你喜欢
![[C语言]用结构体按分数高低降序输出学生的姓名和分数](/img/41/b9dba88941560b296f4d7153b7c684.png)
[C语言]用结构体按分数高低降序输出学生的姓名和分数
![[Golang]力扣Leetcode - 349. 两个数组的交集(哈希表)](/img/92/03de54c9f08eae5bc920b04d2b8493.png)
[Golang]力扣Leetcode - 349. 两个数组的交集(哈希表)

Introduction to social engineering practice

牛客刷题——两种排序方法

EasyCwmp源码分析

Retrofit source code analysis

Reading summary of nacos2.x source code
![[golang] leetcode - 349 Intersection of two arrays (hash table)](/img/92/03de54c9f08eae5bc920b04d2b8493.png)
[golang] leetcode - 349 Intersection of two arrays (hash table)

使用Visdom對損失函數進行監控
![[c language] limit the number of searches and output the maximum value found in the number of internal searches](/img/e6/cbb8dd54b49ade453251a70c8455e8.png)
[c language] limit the number of searches and output the maximum value found in the number of internal searches
随机推荐
力扣31 下一个排列
力扣32题最长有效括号
TR-069协议介绍
[C语言]用结构体按分数高低降序输出学生的姓名和分数
Nocturnal installs APK and BP agent
Feign 共享登录信息进行请求
01.电信_领域业务经验
炫酷的可视化工具:processing 初识
LDPC 7 - 解码简单例子
ubuntu 安装psql以及运行相关命令
[C语言]用结构体把输入的指定分数范围内的学生输出
Codeworks round 479 (Div. 3) [done]
Ctfhub SQL Boolean blind annotation
Explain AI accelerators in detail: GPU, DPU, IPU, TPU... There are infinite possibilities for AI acceleration schemes
5 minutes to understand the red, blue and purple in the attack and defense drill
SISO Decoder for min-sum(补充章节2)
高并发架构设计
Understanding of distributed transactions
[pat grade B question bank] complete summary
網絡安全威脅情報體系