12. Integer to Roman [Integer Variable Roman numerals]

Description
character number
I. 1
V. 5
X-10
L 50
C 100
D 500
M 1000
left I can be placed V (5) and X (10), and to represent 4 and 9.
X L can be placed on the left (50) and C (100), and 40 and 90 are represented.
C may be on the left D (500) and M (1000), and 400 and 900 are represented

Examples of
Here Insert Picture Description
ideas

  • method 1
  • Method 2

answer

  • python
*方法1*
class Solution:
    def intToRoman(self, n: int) -> str:
        d={1:'I',4:'IV',5:'V',9:'IX',10:'X',40:'XL',50:'L',90:'XC',100:'C',400:'CD',500:'D',900:'CM',1000:'M'}
        s=''
        i=1000
        while i>0:
            if n//i==9:
                n-=9*i
                s+=d[9*i]
            if n//i>=5:
                n-=5*i
                s+=d[5*i]
            if n//i==4:
                n-=4*i
                s+=d[4*i]
            if n//i<=3 and n>=i:
                n-=i
                s+=d[i]
            if n<i:
                i=i//10
        return s
        
*方法2*
class Solution:
    def intToRoman(self, num: int) -> str:
        M = ["", "M", "MM", "MMM"]
        C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
        X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
        I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
        return M[num//1000]+C[(num%1000)//100]+X[(num%100)//10]+I[num%10]
  • c++
*方法1*
class Solution {
public:
    string intToRoman(int n) {
        unordered_map<int, string> d={{1,"I"},{4,"IV"},{5,"V"},{9,"IX"},{10,"X"},{40,"XL"},{50,"L"},{90,"XC"},{100,"C"},{400,"CD"},{500,"D"},{900,"CM"},{1000,"M"}};
        int i = 1000;
        string s("");
        while (i>0)
        {
            
            if (n/i==9)
            {
                s+=d[9*i];
                n-=9*i;
            }
            if (n/i>=5)
            {
                s+=d[5*i];
                n-=5*i;
            }
            if (n/i==4)
            {
                s+=d[4*i];
                n-=4*i;
            }
            if (n/i>=1 && n/i<=3)
            {
                s+=d[i];
                n-=i;
            }
          
            if (n<i)
                i /= 10;
      
        }
        return s;
        
    }
};
*方法2*
class Solution {
public:
    string intToRoman(int num) {
        string M[4] = {"", "M", "MM", "MMM"};
        string C[10] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        string X[10] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        string I[10] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        
        return M[num/1000]+C[(num%1000)/100]+X[(num%100)/10]+I[num%10];
    }
};
Published 78 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/puspos/article/details/103032623