编程:分别实现atoi函数和itoa函数

要求1:自定义一个函数,实现整型转字符串,要求不能使用itoa函数。
代码实现

void IntToStr(unsigned char* str, unsigned int intnum)
{
    unsigned int Div = 1000000000, j = 0, Status = 0;
   //32位无符号数最大是10位整数,所以Div=10 0000 0000
    for (unsigned int i = 0; i < 10; i++)
    {
        str[j++] = (intnum / Div) + '0';//取最高位 转化成字符 
 
        intnum = intnum % Div;//去掉最高位
        Div /= 10;//还剩下10-i位要转换
        if ((str[j-1] == '0') & (Status == 0))//忽略最高位的'0'
        {
            j = 0;
        }
        else
        {
            Status++;
        }
    }
}

要求2:自定义一个函数,实现字符串转整型,要求不能使用atoi函数。
代码实现

int strToint( char* str)
{
    int temp = 0;
    const char* p = str;
    if(str == NULL) return 0;
    if(*str == '-' || *str == '+')
    {
        str ++;
    }
    while( *str != 0)
    {
        if( *str < '0' || *str > '9')
        {
            break;
        }
        temp = temp*10 +(*str -'0');
        str ++;
    }
    if(*p == '-')
    {
        temp = -temp;
    }
    return temp;
}

猜你喜欢

转载自blog.csdn.net/QIJINGBO123/article/details/88393807