微软笔试题itoa

kernelkoder 2013-10-21 04:20:35
Convert integer to decimal representation
Write a function to convert an integer n into its ASCII string representation for a given base
The function must be implemented in a portable way that covers all possible values of n, and all bases between 2 and 16.
You are not allowed to use any library functions (given that this is a function that is included in the standard C library).


char* itoa(int n, int base)
{
// e.g. itoa(123, 10) returns the null-terminated
// string "123"
...
}

If you would like to implement the solution in C#, consider the following signature:
public string itoa(int n, int base);
...全文
107 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
测试NULL 2013-10-23
  • 打赏
  • 举报
回复

char* itoa(int i, int radix)
{
    // 考虑了32位的二进制 
    static char local[33];
    char *p = &local[32];
    int sign = 0;
    unsigned int tmp;
    static unsigned char table[] = "0123456789abcdef";

    if ( radix < 2 || radix > 16 )
    {
        *p = '\0';
        return p;
    }

    // 十进制才有"负数"之说 
    if (i < 0 && radix == 10)
    {
        i = -i;
        sign = 1;
    }

    // 其它进制,强制转换成无符号类型 
    tmp =  i;

    // 逆序保存 
    *p-- = '\0';
    do {
        *p-- = table[tmp % radix];
        tmp /= radix;
    } while (tmp > 0);

    if (sign)
    {
        *p-- = '-';
    }
    return p + 1;
}

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧