将数字转化为大写汉字的字符串

测试截图:

将数字转化为大写汉字的字符串_第1张图片

// 将数字number转化为大写汉字组成的字符串,没有零,如果对内存要求高,则要修改接口处理string::operator+

bool ConvertToString(int number,std::string& str)
{
	static const char* codes[]   ={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
	static const char* danwei[4] ={"千","百","十",""};
	static const char* danwei2[3]={"亿","万",""};
	static const int wan = 10000;
	static const int yi  = wan*wan;
	if(number<10000)
	{
		if(number<=0)
			return false;

		const int nums[4]={(number/1000)%10,(number/100)%10,(number/10)%10,number%10};
		for(int i=0;i<4;i++)
		{
			int digit = nums[i];
			if(digit!=0)
				str += std::string(codes[digit])+danwei[i];
		}
		return true;
	}else
	{
		int nums[3];
		nums[0]=number/yi;
		nums[1]=(number-nums[0]*yi)/wan;
		nums[2]=(number-nums[0]*yi-nums[1]*wan);
		for (int i=0;i<3;i++)
		{
			if(ConvertToString(nums[i],str))
				str+=danwei2[i];
		}
		return true;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	for (int i=0;i<1000;i++)
	{
		
		std::string str ;
		srand(time(0)+i*i);
		int num1 = rand();
		srand(time(0)+i*i+num1);
		int num2 = rand();

		num2 = num1*num2;
		ConvertToString(num2,str);
		printf("%d\t%d\t%s\n",i,num2,str.c_str());
	}
	return 0;
}


你可能感兴趣的:(算法)