当前位置:网站首页>C language force buckle the eighth question of string conversion integer. Ergodic method
C language force buckle the eighth question of string conversion integer. Ergodic method
2022-07-25 00:15:00 【Take care of two dogs and never let them go bad】
Please come to realize a myAtoi(string s) function , Enable it to convert a string to a 32 Bit signed integer ( similar C / C++ Medium atoi function ).
function myAtoi(string s) The algorithm is as follows :
Read in strings and discard useless leading spaces
Check the next character ( Suppose you haven't reached the end of the character yet ) Positive or negative , Read the character ( If there is ). Determine whether the final result is negative or positive . If neither exists , Suppose the result is positive .
Read in the next character , Until you reach the next non numeric character or the end of the input . The rest of the string will be ignored .
Convert the numbers read in the previous steps into integers ( namely ,"123" -> 123, "0032" -> 32). If you don't read in the numbers , Then the integer is 0 . Change the symbol if necessary ( From step 2 Start ).
If the number of integers exceeds 32 Bit signed integer range [−2^31, 2^31 − 1] , You need to truncate this integer , Keep it in this range . say concretely , Less than −2^31 The integer of should be fixed to −2^31 , Greater than 2^31 − 1 The integer of should be fixed to 2^31 − 1 .
Returns an integer as the final result .
Be careful :
The white space character in this question only includes the space character ' ' .
Except for the leading space or the rest of the string after the number , Do not ignore Any other character .
Example 1:
Input :s = "42"
Output :42
explain : The bold string is the character that has been read in , The caret is the character currently read .
The first 1 Step :"42"( No characters are currently read in , Because there are no leading spaces )
The first 2 Step :"42"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
The first 3 Step :"42"( Read in "42")
Parse to get an integer 42 .
because "42" In scope [-231, 231 - 1] Inside , The final result is 42 .
Example 2:
Input :s = " -42"
Output : - 42
explain :
The first 1 Step :" -42"( Read in leading space , But ignore )
The first 2 Step :" -42"( Read in '-' character , So the result should be negative )
The first 3 Step :" -42"( Read in "42")
Parse to get an integer - 42 .
because "-42" In scope [-231, 231 - 1] Inside , The final result is - 42 .
Example 3:
Input :s = "4193 with words"
Output :4193
explain :
The first 1 Step :"4193 with words"( No characters are currently read in , Because there are no leading spaces )
The first 2 Step :"4193 with words"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
The first 3 Step :"4193 with words"( Read in "4193"; Because the next character is not a number , So read in stop )
Parse to get an integer 4193 .
because "4193" In scope [-231, 231 - 1] Inside , The final result is 4193 .
source : Power button (LeetCode)
link :https ://leetcode.cn/problems/string-to-integer-atoi
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Numbers 0 To 9 Of ASCII The code values are respectively 48 To 57;
Pay attention to three points 1. Minus question 2. Spillover problem 3. Illegal character judgment
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int test(char * s)
{
int out = 0;// Output
int len = strlen(s);// String length
int i = 0;// Traverse the parameters of the string
int pos = 1;// Judge positive and negative , If there is no positive or negative, the default is 1, That is, the default positive number
int max = 2147483647;
int min = -max - 1;
if (len == 0)
return 0;
while (s[i]<'0'||s[i]>'9')// Loop the non numeric characters before
{
if (s[i] == ' '||((s[i]<'0' || s[i]>'9')&&s[i]!='+'&&s[i] != '-'))// If it is a space, continue to the next
i++;
if (s[i] == '-')// Judge whether it is a negative number
{
pos = -1;
i++;
}
if (s[i] == '+'&&pos == 1)// Determine whether it is a positive number And throw it away “+-12” The impact of such situations
{
pos = 1;
i++;
}
if (s[i] == '+'&&pos == -1)// Determine whether it is a positive number And throw it away “+-12” The impact of such situations
{
pos = -1;
i++;
}
}
while (s[i + 1]>='0' && s[i + 1]<='9')
{
out = out * 10 + s[i] - '0';
i++;
}
out = pos * out;
// The following is to judge whether it overflows
if (out > 0)
{
if (out > max / 10 || (out == max / 10 && (s[i] - '0') > max % 10))
return max;
else
out = out * 10 + s[i] - '0';
}
if (out < 0)
{
if (out < min / 10 || (out == min / 10 && ('0' - s[i]) < min % 10))
return min;
else
out = out * 10 - s[i] + '0';
}
return out;
}
int test2(char * s) {
int i = 0;
int out = 0;
int pol = 1;
int len = strlen(s);
if (len == 0) return 0;
while (s[i] == ' ') i++; // Delete the blank space
if (s[i] == '-') { // Judge positive and negative
pol = -1;
i++;
}
else if (s[i] == '+') {
pol = 1;
i++;
}
else {
pol = 1;
}
while (s[i] != '\0') {
if (s[i]<'0' || s[i]>'9') { // Illegal character check
i++;
break;
}
if (out > INT_MAX / 10) return (pol > 0 ? INT_MAX : INT_MIN); // Cross border judgment
if (out == INT_MAX / 10) {
if (pol > 0 && s[i] > '7') return INT_MAX;
else if (pol < 0 && s[i] >= '8') return INT_MIN;
}
// The following should be written normally out=10*out+(s[i]-'0'), The reason for subtracting '0',
// To prevent 10*out+s[i] Transboundary
out = 10 * out - '0' + s[i];
// Because this topic is not allowed 64 Bit stored data , So illegal judgment can be simpler
// You can directly out Defined as long type , Just judge directly
//if(pol*out>INT_MAX) return INT_MAX;
//if(pol*out<INT_MIN) return INT_MIN;
i++;
}
out = out * pol;
return out;
}
int main()
{
char s[20] = "wwww -42";
//printf("%d", strlen(s));
int out = 0;
//out = test(s);
out = test2(s);
printf("%d", out);
return 0;
}another : My test The function cannot pass the force deduction . The output displayed on the force buckle is 0, But in vs The compiler has no problems with any of the samples , Is there a boss to guide the problem ...
边栏推荐
- SQL file import database - Nanny level tutorial
- 云计算三类巨头:IaaS、PaaS、SaaS,分别是什么意思,应用场景是什么?
- [acwing weekly rematch] 61st weekly 20220723
- [mindspore ascend] [running error] graph_ In mode, run the network to report an error
- LP liquidity pledge mining system development detailed procedure
- Coding builds an image, inherits the self built basic image, and reports an error unauthorized: invalid credential Please confirm that you have entered the correct user name and password.
- Promtool Check
- Managing databases in a hybrid cloud: eight key considerations
- 如果实现与在线CAD图中的线段实时求交点
- [untitled]
猜你喜欢

91. (leaflet chapter) leaflet situation plotting - offensive direction drawing
![[leetcode weekly replay] 303rd weekly 20220724](/img/ba/0f16f1f42e4a2593ec0124f23b30d7.png)
[leetcode weekly replay] 303rd weekly 20220724

Grafana - influxdb visual K6 output

Advanced function of postman

How to put long links into Excel

Be an artistic test / development programmer and slowly change yourself

WP wechat export chat record backup to computer
![[mindspore ascend] [running error] graph_ In mode, run the network to report an error](/img/81/9e96182be149aef221bccb63e1ce96.jpg)
[mindspore ascend] [running error] graph_ In mode, run the network to report an error
![[hero planet July training leetcode problem solving daily] 24th line segment tree](/img/ae/1f3288a99cb07fcbb1836357e0229a.png)
[hero planet July training leetcode problem solving daily] 24th line segment tree

Pointers and arrays
随机推荐
【无标题】
Use SQLite provided by the system
MySQL common basic commands
Opengauss kernel analysis: query rewriting
Redis memory analysis tool RMA usage
What are the meanings and application scenarios of the three giants of cloud computing: IAAs, PAAS and SaaS?
Nodejs package
Where are MySQL version numbers 6 and 7?
Flash send email
[mindspore] [xception model] script statement is suspected to be wrong
Sql文件导入数据库-保姆级教程
Use of serial queues
Fast development board for Godson solid state drive startup (burning system to solid state) - partition
Pointers and arrays
Install K6 test tool
Beisen prospectus: the advantages of the track are prominent, and integration + medium and large customers are plus points
Soft test --- fundamentals of programming language (Part 2)
91. (leaflet chapter) leaflet situation plotting - offensive direction drawing
Regular expression learning
Qt学习-利用数据库单例完成 登录匹配 + 注册 功能实现