LeetCode Integer to Roman

链接: https://oj.leetcode.com/problems/integer-to-roman/


题目上已经说最大出现的整型值为3999,这样就很简单了。

class Solution
{
	public:
		string intToRoman(int num)
		{
			string ans;
			char str_num[8];
			sprintf(str_num,"%d",num);				//the max num is 3999
			int n=strlen(str_num);
			for(int i=0;i<n;i++)
			{
				int t=str_num[i]-'0';
				if(n-i==4)
				{
					for(int j=0;j<t;j++)
						ans+="M";			//1000
				}
				if(n-i==3)
				{
					if(t==9)
						ans+="CM";			//900
					else if(t==4)
						ans+="CD";			//400
					else
					{
						if(t>=5)
						{
							ans+="D";		//500
							for(int j=0;j<t-5;j++)
								ans+="C";		//100
						}
						else
						{
							for(int j=0;j<t;j++)
								ans+="C";		//100
						}
					}

				}
				if(n-i==2)
				{
					if(t==9)
						ans+="XC";		//90
					else if(t==4)
						ans+="XL";		//40
					else
					{
						if(t>=5)
						{
							ans+="L";	//50
							for(int j=0;j<t-5;j++)
								ans+="X";		//10
						}
						else
						{
							for(int j=0;j<t;j++)
								ans+="X";			//10
						}
					}
				}			
				if(n-i==1)
				{
					if(t==9)
						ans+="IX";			//9
					else if(t==4)
						ans+="IV";			//4
					else
					{
						if(t>=5)
						{
							ans+="V";		//5
							for(int j=0;j<t-5;j++)
								ans+="I";
						}
						else
						{
							for(int j=0;j<t;j++)
								ans+="I";
						}
					}
				}
			}
			return ans;
		}
		
};


原文地址:https://www.cnblogs.com/frankM/p/4399431.html