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 };
  • 相关阅读:
    Using Redis as Django's session store and cache backend
    Celery 和 Redis 入门
    centos 安装 rabbitmq
    CentOS 6 安装 Python3.5以及配置Django
    python metaclass 入门简介
    uWSGI其三:uWSGI搭配Nginx使用
    CentOS 6.5 安装 Nginx 1.7.8 教程
    基于nginx和uWSGI在Ubuntu上部署Djan
    CentOS 6.5 下安装 Redis 2.8.7
    查看Selinux和关闭Selinux
  • 原文地址:https://www.cnblogs.com/easonliu/p/3654182.html
Copyright © 2011-2022 走看看