1. 程式人生 > 其它 >力扣 題目13- 羅馬數字轉整數

力扣 題目13- 羅馬數字轉整數

題目


題解


方法1:用Map形成羅馬字母與整數的對映關係 然後從右往左遍歷 如果下一個小於等於自身就為加 下一個 大於自身就為減

方法2:將羅馬數字拆分成整數位數的形式 然後再用上一題的表格的思想 返回下標再乘以位數(10的次方)即可

程式碼


 

方法1:

#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string, int>m = {
    pair<string, int>("I", 1),
    pair<string
, int>("V", 5), pair<string, int>("X", 10), pair<string, int>("L", 50), pair<string, int>("C", 100), pair<string, int>("D", 500), pair<string, int>("M", 1000), }; int second(char s) { string ss = ""; ss = ss + s; map<string, int>::iterator pos = m.find(ss);
return (*pos).second; } class Solution { public: int romanToInt(string s) { int ans = 0; for (int i = 0; i < s.size(); i++) { int value = second(s[i]); if (i < s.size() - 1 && value < second(s[i + 1])) { ans -= value; }
else { ans += value; } } return ans; } }; int main() { Solution sol; string Rome = "MCMXCIV"; int integer=sol.romanToInt(Rome); cout << integer << endl; }

方法2:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<string> thousands2 = { "", "M", "MM", "MMM" };
vector<string> hundreds2 = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
vector<string> tens2 = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
vector<string> ones2 = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
const string thousands="M";
const string hundreds = "CDM";
const string tens = "XLC";
const string ones = "IVX";
int ergodic(string &Number,vector<string> &Rome) {
    int subscript=0;
    for (int i = 0; i < Rome.size(); i++) {
        if (Number == Rome[i]) {
            subscript = i;
            break;
        }
    }
    return subscript;
}
class Solution {
public:
    int romanToInt(string s) {
        bool digit[4] = { 1,1,1,1 };
        int integer = 0;
        string thousands3="";
        string hundreds3 = "";
        string tens3 = "";
        string ones3 = "";
        for (int i = 0; i < s.size();i++) {
                if (thousands.find(s[i])!=-1&& digit[0]) {
                    thousands3 = thousands3 + s[i];
                }
                else if (hundreds.find(s[i]) != -1 && digit[1]) {
                    hundreds3 = hundreds3 + s[i];
                    digit[0] = 0;
                }
                else if (tens.find(s[i]) != -1 && digit[2]) {
                    tens3 = tens3 + s[i];
                    digit[1] = 0;
                }
                else if (ones.find(s[i]) != -1 && digit[3]) {
                    ones3 = ones3 + s[i];
                    digit[2] = 0;
                }
            }
        integer = ergodic(thousands3, thousands2)*1000 + ergodic(hundreds3, hundreds2)*100 + ergodic(tens3, tens2)*10 + ergodic(ones3, ones2);
        return integer;
    }
};

int main() {
    Solution sol;
    string Rome = "IV";
    int integer=sol.romanToInt(Rome);
    cout << integer << endl;

}