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.

    纯模拟:

    基本字符
    I
    V
    X
    L
    C
    D
    M
    相应的阿拉伯数字表示为
    1
    5
    10
    50
    100
    500
    1000
    1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
    2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
    3. 小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
    4. 正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
    5. 在一个数的上面画一条横线,表示这个数扩大1000倍。
    • 个位数举例
      Ⅰ,1 】Ⅱ,2】 Ⅲ,3】 Ⅳ,4 】Ⅴ,5 】Ⅵ,6】Ⅶ,7】 Ⅷ,8 】Ⅸ,9 】
    • 十位数举例
      Ⅹ,10】 Ⅺ,11 】Ⅻ,12】 XIII,13】 XIV,14】 XV,15 】XVI,16 】XVII,17 】XVIII,18】 XIX,19】 XX,20】 XXI,21 】XXII,22 】XXIX,29】 XXX,30】 XXXIV,34】 XXXV,35 】XXXIX,39】 XL,40】 L,50 】LI,51】 LV,55】 LX,60】 LXV,65】 LXXX,80】 XC,90 】XCIII,93】 XCV,95 】XCVIII,98】 XCIX,99 】
    • 百位数举例
      C,100】 CC,200 】CCC,300 】CD,400】 D,500 】DC,600 】DCC,700】 DCCC,800 】CM,900】 CMXCIX,999】
    • 千位数举例
      M,1000】 MC,1100 】MCD,1400 】MD,1500 】MDC,1600 】MDCLXVI,1666】 MDCCCLXXXVIII,1888 】MDCCCXCIX,1899 】MCM,1900 】MCMLXXVI,1976】 MCMLXXXIV,1984】 MCMXC,1990 】MM,2000 】MMMCMXCIX,3999】
     1 class Solution {
     2 public:
     3     void setDigit(string &res, int n, char a, char b, char c) {
     4          if (n < 4) {
     5             for (int i = 0; i < n; ++i) {
     6                 res.push_back(a);
     7             }
     8         }
     9         if (n == 4) {
    10             res.push_back(a); 
    11             res.push_back(b);
    12         }
    13         if (n == 5) res.push_back(b);
    14         if (n > 5 && n < 9) {
    15             res.push_back(b);
    16             for (int i = 5; i < n; ++i) {
    17                 res.push_back(a);
    18             }
    19         }
    20         if (n == 9) {
    21             res.push_back(a);
    22             res.push_back(c);
    23         }
    24     }
    25     string intToRoman(int num) {
    26         int t = (num / 1000) % 10, h = (num / 100) % 10, d = (num / 10) % 10, n = num % 10;
    27         string res;
    28         setDigit(res, t, 'M', '?', '?');
    29         setDigit(res, h, 'C', 'D', 'M');
    30         setDigit(res, d, 'X', 'L', 'C');
    31         setDigit(res, n, 'I', 'V', 'X');
    32         return res;
    33     }
    34 };
  • 相关阅读:
    跟我学android—01.SplashActivity
    eclipse android : A project with that name already exists in the workspace
    冬吴相对论锦言佳句--0005.薄伽梵歌与“印度式管理”
    [转载]Jquery Form插件表单参数
    Form表单学习网站
    [转载]JQuery获取元素文档大小、偏移和位置和滚动条位置的方法集合
    jquery捕捉文本域输入事件
    [转载]js 遍历数组对象
    C#跳出循环的几种方法的区别
    [转载]MVC3缓存:使用页面缓存
  • 原文地址:https://www.cnblogs.com/easonliu/p/3654182.html
Copyright © 2011-2022 走看看