实现整数转成字符串

来源:互联网 发布:和讯黄金软件 编辑:程序博客网 时间:2024/05/16 02:00

实现整数转成字符串

题目

用 C 语言实现,将一个整数转成字符串,比如 123 转成“123”。要求不能使用 itoa 等函数。

代码

#include <stdio.h>#include <stdlib.h>#include <string.h>char * itostr(int v){    int a;    if(v < 0)    {        a = -v;    }    else    {        a = v;    }    char *str = (char*)malloc(32);    memset(str, 0, 32);    int i = 0;    while(a!=0)    {        int tem = a % 10;        a /= 10;        str[i++] = '0' + tem;    }    if(v < 0)    {        str[i++] = '-';    }    char *str2 = (char*)malloc(i);    int j = 0;    for(; j < i; j++)    {        str2[j] = str[i-j-1];        //printf("%c", str2[j]);    }    str2[j] = '\0';    free(str);    return str2;}int main(){    printf("%s\n", itostr(123));    printf("%s\n", itostr(-123456));    printf("%s\n", itostr(2147483647)); // 2*31-1    return 0;}

这里写图片描述

另一种取巧的方法,如果可以使用 sprintf

#include <stdio.h>#include <stdlib.h>#include <string.h>char * itostr(int v){    char *str = (char*)malloc(32);    memset(str, 0, 32);    sprintf(str, "%d", v);    return str;}int main(){    printf("%s\n", itostr(123));    printf("%s\n", itostr(-123456));    printf("%s\n", itostr(2147483647)); // 2*31-1    return 0;}

测试结果相同。

0 0