LeetCode 12. Integer to Roman numeral 13. Roman numeral to Integer (base conversion, greedy, analog)

12. Integer to Roman numeral

  • From high to low
class Solution {
    
    
public:
    string intToRoman(int num) {
    
    
        int values[] = {
    
    1000,900,500,400,100,90,50,40,10,9,5,4,1};
        string symbols[] = {
    
    "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};    
        string ans = "";
        for(int i=0;i<13 && num>0;i++){
    
    
            while(values[i]<=num){
    
    
                num -= values[i];
                ans += symbols[i];
            }
        }
        return ans; 
    }
};
  • From low to high
class Solution {
    
    
public:
    string intToRoman(int num) {
    
    
        map<int,string> mp = {
    
    {
    
    4,"IV"},{
    
    9,"IX"},{
    
    40,"XL"},{
    
    90,"XC"},{
    
    400,"CD"},{
    
    900,"CM"},{
    
    1,"I"},{
    
    5,"V"},{
    
    10,"X"},{
    
    50,"L"},{
    
    100,"C"},{
    
    500,"D"},{
    
    1000,"M"}};
        if(mp.count(num)) return mp[num];
        stack<string> st;
        int p = 1;
        while(num){
    
    
            int x = num%10;
            if(x==4){
    
    
                st.push(mp[x*p]);
            }else if(x==9){
    
    
                st.push(mp[x*p]);
            }else if(x>=5){
    
    
                for(int i=0;i<x-5;i++){
    
    
                    st.push(mp[p]);
                }
                st.push(mp[5*p]);
            }else {
    
    
                for(int i=0;i<x;i++){
    
    
                    st.push(mp[p]);
                }
            }
            p *= 10;
            num /= 10;
        }
        string ans = "";
        while(!st.empty()){
    
    
            ans += st.top();
            st.pop();
        }
        return ans;
    }
};

13. Convert Roman Numerals to Integers

class Solution {
    
    
public:
    int romanToInt(string s) {
    
    
        map<char,int> cs = {
    
    
            {
    
    'I',1},
            {
    
    'V',5},
            {
    
    'X',10},
            {
    
    'L',50},
            {
    
    'C',100},
            {
    
    'D',500},
            {
    
    'M',1000}
        };
        int num = 0;
        for(int i=0;i<s.size();i++){
    
    
            if(i+1<s.size() && cs[s[i]]<cs[s[i+1]]){
    
    
                num += cs[s[i+1]]-cs[s[i]];
                i++;
            }else{
    
    
                num += cs[s[i]];
            }
        }
        return num;
    }
};

Guess you like

Origin blog.csdn.net/qq_44846324/article/details/108113409