zoukankan      html  css  js  c++  java
  • [LeetCode] Integer to Roman

    Given an integer, convert it to a roman numeral.

    Input is guaranteed to be within the range from 1 to 3999.

    string intToS(int cur,string s,int base,map<int,string> &mDic)
    {
        if(cur==9 || cur==4 || cur==5 || cur==1)
            s += mDic[cur*base];
        else
        {
            if(cur>5)
            {
                s += mDic[5*base];
                cur -= 5;
            }
            for(int i=0;i<cur;i++)
                s +=mDic[base];
    
        }
        return s;
    
    }
    class Solution {
    public:
        string intToRoman(int num) {
    
            map<int,string> mDic;
            mDic[1]="I";
            mDic[5]="V";
            mDic[10]="X";
            mDic[50]="L";
            mDic[100]="C";
            mDic[500]="D";
            mDic[1000]="M";
            mDic[4]="IV";
            mDic[9]="IX";
            mDic[40]="XL";
            mDic[90]="XC";
            mDic[400]="CD";
            mDic[900]="CM";
            int cur = 0,base;
            string s0 = "";
    
            if(num>=1000)//处理千位
            {
                cur = num/1000;
                for(int i=0;i<cur;i++)
                    s0 += mDic[1000];
                num -= cur*1000;
            }
            if(num>=100)//处理百位
            {
                cur = num/100;
                num -=  cur*100;
                base = 100;
                s0 = intToS(cur,s0,base,mDic);
            }
            if(num>=10)//处理十位
            {
                cur = num/10;
                num -= cur*10;
                base =10;
                s0 = intToS(cur,s0,base,mDic);
            }
            if(num>0)//处理个位
            {
                cur = num;
                base = 1;
                s0 = intToS(cur,s0,base,mDic);
            }
            return s0;
        }
    };

    有可以使代码看起来更简单的方法,LeetCode的Discuss可以看一看。

  • 相关阅读:
    java各种框架的比较,分析
    HTTP请求响应码
    jersey获取各个参数的总结
    web项目中各种路径的获取
    netsh学习
    解决sqlplus: command not found
    win10 提速
    解决win10 64位系统可用2.99g
    Windows10关闭SearchUI.exe进程的方法
    msf payload
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3859727.html
Copyright © 2011-2022 走看看