当前位置:网站首页>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 ...
边栏推荐
- Implement a avatar looping control
- Paper time review MB2: build a behavior model for autonomous databases
- Restructuredtext grammar summary for beginners
- Managing databases in a hybrid cloud: eight key considerations
- 你还在使用System.currentTimeMillis()?来看看StopWatch吧
- Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
- [mindspore] [mode] spontaneous_ The difference between mode and graph mode
- Use es to realize fuzzy search and search recommendation of personal blog
- 2022 最 NB 的 JVM 基础到调优笔记, 吃透阿里 P6 小 case
- Advanced function of postman
猜你喜欢

Sql文件导入数据库-保姆级教程

阿里 Seata 新版本终于解决了 TCC 模式的幂等、悬挂和空回滚问题

UART

First experience of flask

Improve static loading dynamic loading

Redis6.2 SYSTEMd startup prompt redis service: Failed with result ‘protocol‘.

Live broadcast preview | online seminar on open source security governance models and tools

【无标题】

The new version of Alibaba Seata finally solves the idempotence, suspension and empty rollback problems of TCC mode

EF core :自引用的组织结构树
随机推荐
Multithreading & high concurrency (the latest in the whole network: interview questions + map + Notes) the interviewer is calm
Promtool Check
EF core :自引用的组织结构树
LP liquidity pledge mining system development detailed procedure
Promtool Check
Analyzing the principle of DNS resolution in kubernetes cluster
WP wechat export chat record backup to computer
Processing PDF and JPG files in VB6
Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
Only by learning these JMeter plug-ins can we design complex performance test scenarios
Sql文件导入数据库-保姆级教程
Leetcode 0125. validate palindrome string
Advanced function of postman
Development direction and problems of optaplanner
50 places are limited to open | with the news of oceanbase's annual press conference coming!
Pit record: typeerror:'module'object is not callable
Discussion on line segment tree
GUI basic application
Tencent low code platform is officially open source! You can drag and drop and generate mobile phone projects and PC projects! Get private benefits
2. Load test