当前位置:网站首页>[sword finger offer] - explain the library function ATOI and simulate the realization of ATOI function
[sword finger offer] - explain the library function ATOI and simulate the realization of ATOI function
2022-07-29 05:35:00 【Gancheng なつき】
꧁ Hello, everybody ! It is a great honor to have your visit , Let's have a long way to go in programming !꧂
* Blog column :【 The finger of the sword offer】*
Introduction to this article :C In library functions atoi Function details and simulation implementation !
Get to know the author : Aspire to be a great programmer , Xiaobai, who is currently a sophomore in College .
Inspirational terms : The tediousness of programming , Let's study together and become interesting !
Catalog
atoi Function function introduction
atoi Function handling special cases
character string “ + ” And " - "
Simulation Implementation atoi function
Implementation conversion is illegal 0 And legal 0
character string " + " And " - "
Realization atoi Function entire source code
Preface
Let's first introduce , This is together 《 The finger of the sword offer 》 Interview questions .
atoi function , What is it ? I think that's a lot of people's question , When I first saw this function , I'm also confused b Of , But after the detailed explanation of the teacher and his own simulation , It can be said that this function has been groped for about , good , Next, let's introduce atoi Function and how to simulate the implementation atoi function .
atoi Function function introduction
Let's see what's in the Library atoi Functional !
We can see the library function atoi Its function is to convert a string into an integer .
And the header file it uses , yes <stdlib.h>.
Let's look at a piece of code , See how it converts strings to integers .
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[20] = "123456";
int ret = atoi(arr);
printf("%d\n", ret);// With %d In the form of printing
return 0;
}
Running results :
This shows that it really converts strings into integers .
atoi Function handling special cases
Pass null pointer
The program will hang up , like this !
An empty string
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[] = "";
int ret = atoi(arr);
printf("%d\n", ret);// With %d In the form of printing
return 0;
}
Running results :
We can see that when transmitting an empty string , It just returns one 0, Now let's assume this 0 It's an illegal 0.
Space
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[] = " ";// return 0 Suppose this is a legal 0
char arr_1[20] = " 123456";
int ret = atoi(arr);
int ret_1 = atoi(arr_1);
printf("%d\n", ret);// With %d In the form of printing
printf("%d\n", ret_1);
return 0;
}
Running results :
We can see two situations , One is pure transmit space , It's back to 0, Suppose this is a legal 0, When there is a space in front of the string , It will skip spaces , Directly convert the following string to integer .
character string “ + ” And " - "
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[] = "-12345";// return 0 Suppose this is a legal 0
int ret = atoi(arr);
printf("%d\n", ret);// With %d In the form of printing
return 0;
}
Running results :
We can see that it will put the string “+ -” The contents of are converted into integers and printed .
A cross-border visit
The so-called cross-border access is to give a large string , When this string is converted , More than the C According to the language INT_MAX Value or INT_MIN The value of , What does the compiler do !
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[] = "+1234511111111111111";// Returns a large number
int ret = atoi(arr);
printf("%d\n", ret);// With %d In the form of printing
return 0;
}
Running results :
You can see , When crossing the line , It converts a large number , When we simulate the implementation , It can be converted into illegal 0.
Non numeric string
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[] = "-1234abc";
char arr_1[20] = "abcd";// return 0 Suppose this is a legal 0
int ret = atoi(arr);
int ret_1 = atoi(arr_1);
printf("%d\n", ret);// With %d In the form of printing
printf("%d\n", ret_1);
return 0;
}
Running results :
We can see that there are two situations , When it is all non numeric strings , Suppose a legal 0, But when there are other numeric strings , Will not print non numeric strings directly .
Simulation Implementation atoi function
Implementation conversion is illegal 0 And legal 0
We can enumerate constants , Indicates the current status , The default conversion is illegal 0.
enum State
{
VAILD,
INVAILD
}Sta=INVAILD;// Creating variables defaults to illegal
Null pointer
You can add assert() Function assertion , Prevention is null pointer .
assert(str);
An empty string
If you encounter an empty string ( namely ‘\0’ when ), We go straight back 0, At this time 0 It's an illegal 0.
if (*str == '\0')
{
return 0;
}
Space
To judge the blank space, we can use isspace() This function , If it is a space, return 1, Skip spaces directly .( A reference header file is required #include<ctype.h>)
while (isspace(*str))
{
str++;
}
character string " + " And " - "
We can define one flag Record which string is currently encountered , Skip the string again " + " perhaps " - ".
int flag = 1;
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
Nonnumeric character
It can be used isdigit To judge , It's a numeric character , return 1, Enter the code and continue to execute , Otherwise directly return ret;(ret For the return value ).
if (isdigit(*str))
{
ret = ret * 10 + flag * (*str - '0');// Subtract character 0, That's the number 0
}
A cross-border visit
You can see that this string is converted into an integer , Is it greater than INT_MAX Or less than INT_MIN, Illegal return 0.
long long ret = 0;
while (*str != '\0')
{
if (isdigit(*str))
{
ret = ret * 10 + flag * (*str - '0');// Subtract character 0, That's the number 0
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;// Force type to int( The return value of the function is int)
}
str++;
}
Realization atoi Function entire source code
#include<stdio.h>
#include<assert.h>
#include<ctype.h>
#include<stdlib.h>
enum State
{
VAILD,
INVAILD
}Sta=INVAILD;// Creating variables defaults to illegal
int my_atoi(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
while (isspace(*str))
{
str++;
}
int flag = 1;
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
long long ret = 0;
while (*str != '\0')
{
if (isdigit(*str))
{
ret = ret * 10 + flag * (*str - '0');// Subtract character 0, That's the number 0
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;// Force type to int( The return value of the function is int)
}
str++;
}
if (*str == '\0')
{
Sta = VAILD; // The normal conversion is over , To the end of \0
}
return (int)ret;
}
int main()
{
char arr[20] = "-1234";
int ret = my_atoi(arr);
if (Sta == VAILD)
{
printf(" Legal conversion :%d\n", ret);
}
else if (Sta == INVAILD)
{
printf(" Illegal conversion :%d\n", ret);
}
return 0;
}
Conclusion
Simulation Implementation atoi Function will be introduced and simulated , Feel that if you learn a little , You can give the blogger triplicate !!!
边栏推荐
猜你喜欢
[C language series] - three methods to simulate the implementation of strlen library functions
[event preview] cloud digital factory and digital transformation and innovation forum for small and medium-sized enterprises
ClickHouse学习(八)物化视图
无重复字符的最长字串
Day 3
Preemptive appointment | Alibaba cloud shadowless cloud application online conference appointment opens
ClickHouse学习(五)集群操作
省市区三级联动(简单又完美)
·来一篇编程之路的自我介绍吧·
ClickHouse学习(十)监控运行指标
随机推荐
字符类型转换
C language first level pointer
[C language series] - print prime numbers between 100 and 200
相对定位和绝对定位
Summary of the first week
On Paradigm
uniapp组件之tab选项卡滑动切换
Clickhouse learning (IX) Clickhouse integrating MySQL
Alibaba cloud architect details nine trends in the game industry
Topological ordering of a graph of water
The function of using wechat applet to scan code to log in to the PC web of the system
【C语言系列】—三种方法模拟实现strlen库函数的方法
uniapp之常用提示弹框
时间复杂度和空间复杂度
Longest string without duplicate characters
Do students in the science class really understand the future career planning?
Clickhouse learning (XI) clickhouseapi operation
关于局部变量
Occt learning 001 - Introduction
重绘与回流的关系