c函数itoa和atoi实现

1、itoa函数实现

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2.   
  3. void itoa(int i, char *string)  
  4. {  
  5.         int power=0,j=0;  
  6.   
  7.         j=i;  
  8.         for( power=1;j>10;j/=10)  
  9.                 power*=10;  
  10.   
  11.         for(;power>0;power/=10)  
  12.         {  
  13.                 *string++='0'+i/power;  
  14.                 i%=power;  
  15.         }  
  16.         *string='\0';  
  17.         printf("%s\n",string);  
  18. }  
  19. void main()  
  20. {  
  21.         char string[20];  
  22.         itoa(12345, string);  
  23.         printf("%s\n",string);  
  24. }  

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

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

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


2、atoi实现

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int atoi(char *str)  
  2. {  
  3.         if(!str)  
  4.                 return -1;  
  5.         bool bMinus=false;  
  6.         int result=0;  
  7.   
  8.         if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))  
  9.         {  
  10.                if(*str=='-')  
  11.                 bMinus=true;  
  12.                *str++;  
  13.         }  
  14.         while( *str != '\0')  
  15.         {  
  16.                 if('0'> *str || *str>'9')  
  17.                         break;  
  18.                 else  
  19.                         result = result*10+(*str++ - '0');  
  20.         }  
  21.   
  22.         if (*str != '\0')//no-normal end  
  23.                 return -2;  
  24.   
  25.         return bMinus?-result:result;  
  26. }  

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

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

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

测试:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. char *c1 = "12345";  
  2.         char *c2 = "-12345";  
  3.         char *c3 = "bat-123";  
  4.         char *c4 = "+123abc";  
  5.   
  6.   
  7.         printf("c1=%d\n",atoi(c1));  
  8.         printf("c2=%d\n",atoi(c2));  
  9.         printf("c3=%d\n",atoi(c3));  
  10.         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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值