码迷,mamicode.com
首页 > 其他好文 > 详细

实现atoi和itoa

时间:2015-06-01 12:57:41      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

  1 /********************************
  2  * 实现atoi和itoa
  3  ********************************/
  4 #include <stdio.h>
  5 #include <string.h>
  6 #include <stdlib.h>
  7 //将字符串转化为整数
  8 int chartoi(char a)
  9 {
 10     if(a >= 0 || a <= 9)
 11         return a - 0;
 12     else
 13         return 0;
 14 }
 15 
 16 int length(const char *str)
 17 {
 18     int i = 0;
 19     while(str[i])
 20     {
 21         i++;
 22     }
 23     return i;
 24 }
 25 
 26 int myatoi(const char *str)
 27 {
 28     int sum = 0;
 29     int len = length(str);
 30     if(str[0] == -)
 31     {
 32         int i = 1;
 33         for(i = 1; i < len; i++)
 34         {
 35             sum = sum * 10 + chartoi(str[i]);
 36         }
 37         return 0 - sum;
 38     }
 39     else
 40     {
 41         int i = 0;
 42         for(i = 0; i < len; i++)
 43         {
 44             sum = sum * 10 + chartoi(str[i]);
 45         }
 46         return sum;
 47     }
 48 
 49 }
 50 
 51 //将整数转化为字符串
 52 void reverse(char *str)
 53 {
 54     int len = length(str);
 55     int i = 0;
 56     for(i = 0; i < len/2; i++)
 57     {
 58         char temp = str[i];
 59         str[i] = str[len - i -1];
 60         str[len - i -1] = temp;
 61     }
 62 }
 63 
 64 const char* neg_num(char *str)
 65 {
 66     int len = length(str);
 67     int i = 0;
 68     for(i = len; i > 0; i--)
 69     {
 70         str[i] = str[i - 1];
 71     }
 72     str[0] = -;
 73     return str;
 74 }
 75 
 76 const char* myitoa(int num)
 77 {
 78     static char str[100];
 79     memset(str, 0, strlen(str));
 80     int neg = 0; //正负判断符
 81     if(num < 0)
 82     {
 83         neg = 0;
 84         num = 0 - num;
 85     }
 86     else
 87     {
 88         neg = 1;
 89     }
 90 
 91     int i = 0;
 92     while(num)
 93     {
 94         str[i] = num % 10 + 0x30;
 95         num = num / 10;
 96         i++;
 97     }
 98     reverse(str);
 99     if(neg == 0)
100         return neg_num(str);
101     else
102         return str;
103 }
104 
105 int main(void)
106 {
107     printf("Hello World!\n");108 
109     printf("%s\n", myitoa(-1234556));
110     return 0;
111 }

 

实现atoi和itoa

标签:

原文地址:http://www.cnblogs.com/yongssu/p/4543484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!