LeetCode 12. Integer to Roman

Posted dacc123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 12. Integer to Roman相关的知识,希望对你有一定的参考价值。

题目

class Solution 
public:
    int v[7]=1,5,10,50,100,500,1000;
    string s[7]="I","V","X","L","C","D","M";
    string intToRoman(int num) 
        string ans="";
        int x=num;
        while(num)
          
            
            int pos=-1;
            for(int i=0;i<7;i++)
            
                if(num<v[i])
                
                     pos=i-1;
                     break;
                
            
            if(pos==-1)
                pos=6;

            int y=fun2(num);
            if(y!=-1)
            
                ans+=fun(y);
                
                num=num-y;
            else
                 int x=num/v[pos];
            
            for(int i=0;i<x;i++)
                ans+=s[pos];
                
               num=num%v[pos];
              
            
              
        return ans;
        
    
    
    int fun2(int x)
    
        int x2=x;
        int i=0;
        while(x)
        
            x/=10;
            i++;
        
        int y;
        if(i==1)
            y=x2;
        else
            y=(x2/(int)pow(10.0,(i-1)))*((int)pow(10.0,i-1));
        
        if(i==1)
        
            if(y==4)
               return y;
            if(y==9)
                return y;
        
        else 
        
            if(y==40)
                return y;
            if(y==90)
                return y;
            if(y==400)
                return y;
            if(y==900)
                return y;
        
        return -1;
    
    
    string fun(int x)
    
         if(x==4)
            return "IV";
        else if(x==9)
            return "IX";
        else if(x==40)
            return "XL";
        else if(x==90)
            return "XC";
        else if(x==400)
            return "CD";
        else if(x==900)
            return "CM";
        
        return "-1";
    
;

以上是关于LeetCode 12. Integer to Roman的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode12 Integer to Roman

LeetCode12. Integer to Roman

LeetCode 12 Integer to Roman (整数转罗马数字)

[LeetCode] 12. Integer to Roman ☆☆

LeetCode(12) - Integer to Roman

LeetCode 12. Integer to Roman