高效实现整型数字转字符串int2str

将数字转换成字符串有很多方法,现在给出一种高效的实现方法。开阔眼界。

char* int2str(unsigned int values)
{
    const char digits[11] = "0123456789";
    char* crtn = new char[32];
    crtn += 31;
    *crtn = '';
    do 
    {
        *--crtn = digits[values%10];
    } while (values /= 10);

    return crtn;
}

以上是没有考虑那么一点点空间的问题;如果考虑那点空间问题,可以这样做。

char* int2str(unsigned int values)
{
    int len = 0;
	const char digits[11] = "0123456789";
	unsigned int tvalue = values;
	while(tvalue >= 100)
	{
		tvalue /= 100;
		len += 2;
	}
	if (tvalue > 10)
		len += 2;
	else if(tvalue > 0)
		len++;

	char* crtn = new char[len+1];
	crtn += len;
	*crtn = '';
	do 
	{
		*--crtn = digits[values%10];
	} while (values /= 10);

	return crtn;	
}
同样,带符号的整数一样的做法。

生命不止,奋斗不息!
原文地址:https://www.cnblogs.com/huzongzhe/p/6735169.html