整數轉化爲字符串函數

1/

int int2str(int num, char * str, int len)
{
 int sign, count;
 char buf[12] = {0};

 sign = num<0 ? -1:1; //標誌位
 num *= sign;

 for(count=0; num; num/=10, count++) 
  buf[count] = num%10 + 48;

 if(sign<0) buf[count++] = '-';
 if (len < count) return -1;

 while(count)
  *(str++) = buf[count---1];

 return 0;
}
 

2/

做了個不用除法的(不知道效率怎麼樣):

#include <stdio.h>

#define INT_LENGTH 10

int a[INT_LENGTH][9]={
  {1000000000,2000000000,3000000000,4000000000,5000000000,6000000000,7000000000,8000000000,9000000000},
  {100000000,200000000,300000000,400000000,500000000,600000000,700000000,800000000,900000000},
  {10000000,20000000,30000000,40000000,50000000,60000000,70000000,80000000,90000000},
  {1000000,2000000,3000000,4000000,5000000,6000000,7000000,8000000,9000000},
  {100000,200000,300000,400000,500000,600000,700000,800000,900000},
  {10000,20000,30000,40000,50000,60000,70000,80000,90000},
  {1000,2000,3000,4000,5000,6000,7000,8000,9000},
  {100,200,300,400,500,600,700,800,900},
  {10,20,30,40,50,60,70,80,90},
  {1,2,3,4,5,6,7,8,9}
 };


void itoa(int num,char* str)
{
 int i=0,j=0,k=0;
 int b=0;
 while (i<INT_LENGTH && num>0)
 {
  
  while (num<a[i][0])
  {
   if (b) str[k++]='0';
   ++i;
  }
  b=1;
  j=0;
  while (j<9 && num>=a[i][j]) ++j;  //這裏可以考慮二分法查找
  str[k++]='0'+j;
  num-= a[i][j-1];
  ++i;
 }
 
 while (i++<INT_LENGTH) str[k++]='0';
 str[k]='/0';
}

int main()
{
 
 int num;
 int i;
 char str[INT_LENGTH];
 char *sp;
 scanf("%d",&num);

 sp=str;
 if (num==0)
    {
  str[0]='0';
  str[1]='/0';
 }
 else if (num<0)
 {
  str[0]='-';
  num=0-num;
  ++sp;
 }
 if (num) itoa(num,sp);
 
 printf("%s/n",str);
 return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章