• LeetCode#12 Integer to Roman


    Problem Definition:

    Given an integer, convert it to a roman numeral.

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

    Solution:

    1)思路基本上就是这个样子,不过因为输入的整数最大不到4000,所以可以直接把循环给拆了。

     1     # @param {integer} num
     2     # @return {string}
     3     def intToRoman(self, num):
     4         dicIntToRoman={1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
     5         dicIntToArr={1:[1],2:[1,1],3:[1,1,1],4:[1,5],5:[5],6:[5,1],7:[5,1,1],8:[5,1,1,1],9:[1,10]}
     6         pz=1000
     7         roman=''
     8         while num!=0:
     9             a=num/pz
    10             num=num%pz
    11             if a==0:
    12                 pz/=10
    13                 continue
    14             arr=dicIntToArr[a]
    15             for c in arr:
    16                 roman+=dicIntToRoman[pz*c]
    17             pz/=10
    18         return roman

    2)

    1 public static String intToRoman(int num) {
    2         String M[] = {"", "M", "MM", "MMM"};
    3         String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    4         String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    5         String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    6         return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
    7     }
  • 相关阅读:
    [CF1263E] Editor
    [CF1288D] Minimax Problem
    [CF1294E] Obtain a Permutation
    [CF770C] Online Courses In BSU
    [CF832D] Misha, Grisha and Underground
    [CF917B] MADMAX
    [CF938D] Buy a Ticket
    [CF959E] Mahmoud and Ehab and the xor-MST
    [CF999E] Reachability from the Capital
    [CF960F] Pathwalks
  • 原文地址:https://www.cnblogs.com/acetseng/p/4689043.html
Copyright © 2020-2023  润新知