当前位置:网站首页>Niu Ke swipes the question -- converting a string to an integer
Niu Ke swipes the question -- converting a string to an integer
2022-06-11 18:29:00 【HHYX.】
Convert a string to an integer
Topic link : Convert a string to an integer
Title Description
Convert a string to an integer , Library functions that require that integers cannot be converted using strings . Values for 0 Or if the string is not a valid value, it returns 0
Data range : The string length satisfies 0 \le n \le 100 \0≤n≤100
Advanced : Spatial complexity O(1) \O(1) , Time complexity O(n) \O(n)
Be careful :
① Any symbol... May appear in the string , Occurrence Division +/- Output directly when other symbols 0
② Possible in string +/- And can only appear at the beginning of the string .
Input description :
Enter a string , Including alphanumeric symbols , Can be null
Return value description :
If it is a legal numeric expression, it returns the number , Otherwise return to 0
Topic analysis
It is required to convert the string into an integer , Library functions, etc. cannot be used . If the string contains illegal characters, it returns 0. To implement this transformation, you can first judge the sign's positive and negative , The sign can only appear on the first character , So you can judge first . If there is no sign, the string conversion is performed directly . Use a loop to iterate through the string , To convert characters to numbers in turn, you only need to subtract characters from numeric characters 0 that will do , Then sum it up . The summation formula is sum=sum*10+(str[i]-‘0’), So we can find the sum , Finally, calculate according to the positive and negative . The code implementation is as follows :
Code implementation
int StrToInt(string str) {
int i = 0;
int sum = 0;// Return value Integer size
int flag = 1;// Positive and negative judgment basis 1 Representative is 0 It means negative
for (i = 0; i < str.size(); i++)
{
if (i != 0 && (str[i] < '0' || str[i]>'9'))// Illegal characters appear
{
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;
}

边栏推荐
猜你喜欢
随机推荐
MySQL/Redis 常见面试题汇总
力扣31 下一个排列
牛客刷题——求最小公倍数
SISO Decoder for SPC (补充章节1)
vim常用命令
Apipost精妙使用技巧
Ctfhub SQL Boolean blind annotation
Force buckle 34 finds the first and last positions of elements in a sorted array
牛客刷题——part7
HashSet集合存储学生对象并遍历
[untitled]
判断是否为平衡二叉树
论催收系统的管理子系统选型设计
5 minutes to understand the red, blue and purple in the attack and defense drill
使用mysql判断日期是星期几
高并发架构设计
H.264概念
Feign shares login information for request
Force deduction 23 questions, merging K ascending linked lists
[C语言]限制查找次数,输出次数内查找到的最大值




![[C语言]压缩字符串并添加标记字符](/img/b7/f7918f3ee0c409faffc70addd5ee65.png)




![[C语言]用结构体把平均分和低于等于平均分的学生数据输出](/img/c4/263301a22b61c86a3e0df6ad2596f1.png)