当前位置:网站首页>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 ...
边栏推荐
- 1、 MFC introduction
- [LeetCode周赛复盘] 第 303 场周赛20220724
- Two numbers that appear only once in the array
- LeetCode_6124_第一个出现两次的字母
- Efficiency increased by 98%! AI weapon behind operation and maintenance inspection of high altitude photovoltaic power station
- Why does [mindspore ascend] [custom operator] repeatedly assign values to one tensor affect another tensor?
- Why do I have to clean up data?
- 4. Immersion test
- Remember the problem of using redisson to step on the pit once
- 软考 --- 程序设计语言基础(下)
猜你喜欢

ROS manipulator movelt learning notes 3 | kinect360 camera (V1) related configuration

Can Baidu network disk yundetectservice.exe be disabled and closed

Efficiency increased by 98%! AI weapon behind operation and maintenance inspection of high altitude photovoltaic power station
![[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

做一个文艺的测试/开发程序员,慢慢改变自己......

来自大佬洗礼!2022 头条首发纯手打 MySQL 高级进阶笔记, 吃透 P7 有望

UART

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

Advanced function of postman

Sql文件导入数据库-保姆级教程
随机推荐
LeetCode_392_判断子序列
From the big guy baptism! 2022 headline first hand play MySQL advanced notes, and it is expected to penetrate P7
C语言学习之分支与循环语句
Kubernetes application design guide
Install software on kubernetes cluster using helm 3 package manager
Install K6 test tool
LeetCode_6124_第一个出现两次的字母
What are the meanings and application scenarios of the three giants of cloud computing: IAAs, PAAS and SaaS?
[untitled]
多线程&高并发(全网最新:面试题 + 导图 + 笔记)面试手稳心不慌
[LeetCode周赛复盘] 第 303 场周赛20220724
2022 Henan Mengxin League game 2: Henan University of technology I - 22
Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
Qt项目-安防监控系统(各个界面功能实现)
codeforces round #805 ABCDEFG
采坑记录:TypeError: 'module' object is not callable
[leetcode weekly replay] 303rd weekly 20220724
===、==、Object. Is basic package type
C language: deep analysis function stack frame
Shell echo command