当前位置:网站首页>【剑指Offer】模拟实现atoi
【剑指Offer】模拟实现atoi
2022-07-25 06:21:00 【命由己造~】
一、使用方式
int atoi( const char *string );
atoi实现的是字符串转整形的操作:
int main()
{
char arr1[20] = "123456";
char arr2[20] = "-123456";
char arr3[20] = "12abc3456";//遇到非数字停止转换
int ret1 = atoi(arr1);
int ret2 = atoi(arr2);
int ret3 = atoi(arr3);
printf("%d %d %d", ret1, ret2, ret3);
return 0;
}

下面我们就来模拟实现:
二、模拟实现
2.1 常规转换
假设要把字符串"123456"转换成整形:
int ret = 0;
while (*str)
{
ret = ret * 10 + *str - '0';
str++;
}
2.2 要处理的特殊情况
1️⃣ 空指针
2️⃣ 空字符串
3️⃣ 空格
4️⃣ 正负号
5️⃣ 越界
6️⃣ 非数字字符
空字符串:
当我们传递的是空字符串时,我们应该返回什么?
如果返回0,那传递的是字符0时该怎么办?
所以要判断是否合法。
我们可一创建一个枚举变量来判断
enum status
{
VALID,// 0
INVALID// 1
}sta = INVALID;
sta是全局变量,先假设不合法,如果合法,后边再改。
if (*str == '\0')
{
return 0;//非法0
}
空格:
遇到空格如果在字符串开头会自动跳过,如果在字符串中间就是第6️⃣种情况,直接跳过。
if (isspace(*str))//判断是不是字符'0'
{
str++;
}
正负号:
int flag = 1;
if (*str == '+')
{
str++;
}
else if(*str == '-')
{
flag = -1;
str++;
}
非数字字符:
while (*str)
{
if (isdigit(*str))//判断是否为数字字符
{
ret = ret * 10 + *str - '0';
}
else
{
return ret;
}
str++;
}
越界判断:
判断是否越界就是看ret是否大于INT_MAX,对于负数就是小于INT_MIN,要注意int是永远不会超过INT_MAX,应该用long long
if (isdigit(*str))//判断是否为数字字符
{
ret = ret * 10 + flag * (*str - '0');
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;
}
全代码:
enum status
{
VALID,// 0
INVALID// 1
}sta = INVALID;
int my_atoi(const char* str)
{
int flag = 1;
assert(str);
if (*str == '\0')
{
return 0;//非法0
}
if (isspace(*str))//判断是不是字符'0'
{
str++;
}
if (*str == '+')
{
str++;
}
else if(*str == '-')
{
flag = -1;
str++;
}
long long ret = 0;
while (*str)
{
if (isdigit(*str))//判断是否为数字字符
{
ret = ret * 10 + flag * (*str - '0');
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;
}
str++;
}
if (*str == '0')
{
sta = VALID;
}
return (int)ret;
}
int main()
{
char arr[200] = "123abc45";
int ret = my_atoi(arr);
if (sta == INVALID)
{
printf("非法返回: %d", ret);
}
else if (sta == VALID)
{
printf("%d", ret);
}
return 0;
}
边栏推荐
- JS how to delete an element without deleting its child elements
- VB variable types and control statements (basic)
- 都说ScreenToGif是GIF录制神器,却不知其强大之处远不在此
- 你了解PowerBI中的去年同期吗
- Solve the problem of invalid modification of QT 5 interface. Solve the problem of invalid modification of qtdesigner
- Detailed annotation and analysis of start.s of uboot
- ROI pooling and ROI align
- [daily practice] day (14)
- mysql数据库备份和恢复
- Interlocked atom access series of functions
猜你喜欢
![[ultra detailed diagram] FPN + mask RCNN](/img/ef/ddd62fe7e54074c134aa5ee4cc5840.png)
[ultra detailed diagram] FPN + mask RCNN

ROI pooling and ROI align

Sword finger offer 45. arrange the array into the smallest number

In depth analysis: is the hottest business model in 2022 linked by 2+1 a legal model?

"Everyday Mathematics" serial 61: March 1

Amazoncaptcha 95%成功率绕过亚马逊IP验证码
![[unity3d] ugui callback function](/img/6f/312e7f2cf76fa932e66c5ba0737219.png)
[unity3d] ugui callback function

EOL offline sequence based on iso13209 (Otx)

【Node】服务端口被占用Error: listen EADDRINUSE: address already in use :::9000-如何关闭node启动的端口

四、MFC工具栏、运行时类信息机制、运行时创建机制
随机推荐
JTAG debugging source level debugging of arm bare board debugging
JS how to delete an element without deleting its child elements
SAP FICO 第三节 BDC和LTMC导入S4财务科目
Use abp Zero builds a third-party login module (III): web side development
(Niuke multi School II) j-link with arithmetic progress (least square method / three points)
Brief introduction of acoustic filter Market
The most comprehensive multi-threaded application tutorial - summary in detail
Amazoncaptcha bypasses Amazon IP verification code with 95% success rate
VO, dto, do, Po distinction and use
MFC IniFile Unicode mode reading method
[QT] solve the problem of Chinese garbled code output from QT console
What determines the "personality" of AI robots?
(2022牛客多校)D-Link with Game Glitch(spfa)
(16)[系统调用]追踪系统调用(3环)
嵌入式c语言开发之宏定义求两个数的最大值的使用技巧
VSCode 如何开启多个终端?如何横向显示?
Amazoncaptcha 95%成功率绕过亚马逊IP验证码
Machine learning keras fitting sine function
node.express中req.body总是undefind解决
Bug notes