首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

整数转换成字符串itoa函数的实现解决思路

2012-04-17 
整数转换成字符串itoa函数的实现一道面试题,麻烦大侠们给解决下。题目:整数转换成字符串itoa函数的实现要求

整数转换成字符串itoa函数的实现
一道面试题,麻烦大侠们给解决下。
题目:整数转换成字符串itoa函数的实现
要求:不能使用库函数;按给出的函数原型进行编写。
char * itoaTest(int num) ;

[解决办法]

C/C++ code
char * itoaTest(int num){char *index="0123456789";char *str=new char[16];int unum;int i=0,j,k=0;char ch;if(num<0){str[i++]='-';num=-num;k=1;}elseunum=num;do{str[i++]=index[unum%10];unum/=10;}while(unum!=0);str[i]='\0';str+=k;for(j=0;j<(i-k)/2;i++){ch=str[j];str[j]=str[i-j-1];str[i-j-1]=ch;}str-=k;return str;}
[解决办法]
刚才没考虑到负数的情况。
我觉得题目要求的不是很好。
不给函数传指针的话,你就要在函数里开辟空间,然后在其它函数里才能释放掉。
这么做是不好的。
C/C++ code
#include <stdio.h>#include <malloc.h>char * itoaTest(int num){    char *a=(char*)malloc(32);    int count=0,temp,flag=0;    if (num<0)    {        num=-num;        *a='-';        flag=1;        count++;    }    temp=num;    while (temp)    {        temp/=10;        count++;    }    *(a+count)='\0';    while (flag?count-1:count)    {        *(a+(--count))='0'+num%10;        num/=10;    }    return a;}int main(){    char *a;    a=itoaTest(-123456);    printf("%s",a);    free(a);    getchar();} 

热点排行