zoukankan      html  css  js  c++  java
  • 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;
    		}
    		
    };


  • 相关阅读:
    Docker基本命令及工作原理
    Docker安装
    linux命令
    MTPuTTy使用
    SpringBoot--swagger搭建、配置及使用
    idea使用技巧
    Idea插件
    IDEA开发工具使用 git 创建项目、拉取分支、合并分支
    git命令
    javbus爬虫-老司机你值得拥有
  • 原文地址:https://www.cnblogs.com/frankM/p/4399431.html
Copyright © 2011-2022 走看看