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";
    }
};
上一篇:Integer to Roman


下一篇:【“纽劢科技杯”第十六届同济大学程序设计竞赛暨上海邀请赛同步赛】A-张老师数数