c函数itoa和atoi实现

1itoa函数实现

#include <stdio.h>
 
void itoa(int i, char *string)
{
        int power=0,j=0;
 
        j=i;
        for( power=1;j>10;j/=10)
                power*=10;
 
        for(;power>0;power/=10)
        {
                *string++='0'+i/power;
                i%=power;
        }
        *string='\0';
        printf("%s\n",string);
}
void main()
{
        char string[20];
        itoa(12345, string);
        printf("%s\n",string);
} 

其中power相当于类似于1234,其power=1000;134,power=100 

*string++='0'+i/power;//获得取得字符的asicii 

i/power取得字符,例如1234/1000=1;234/100=2 

2atoi实现 

int atoi(char *str)
{
        if(!str)
                return -1;
        bool bMinus=false;
        int result=0;
 
        if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))
        {
               if(*str=='-')
                bMinus=true;
               *str++;
        }
        while( *str != '\0')
        {
                if('0'> *str || *str>'9')
                        break;
                else
                        result = result*10+(*str++ - '0');
        }
 
        if (*str != '\0')//no-normal end
                return -2;
 
        return bMinus?-result:result;
}

重写的atoi函数,没有考虑溢出的情况。 

 if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))//判读第一个字符是否为数字的正负号

if (*str != '\0')//no-normal end,当上文的while循环不正常退出,应视为字符串不合法,例如“+1234abc

测试:

char *c1 = "12345";
        char *c2 = "-12345";
        char *c3 = "bat-123";
        char *c4 = "+123abc";
 
 
        printf("c1=%d\n",atoi(c1));
        printf("c2=%d\n",atoi(c2));
        printf("c3=%d\n",atoi(c3));
        printf("c4=%d\n",atoi(c4));

输出结果为: 

c1=12345

c2=-12345

c3=-2

c4=-2 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法哥2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值