leetcode

题目链接

解题思路:
按照题目逐一进行判断即可。小技巧:是先将这6种情况进行判断,然后在依次判断其他情况。

  • I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
  • X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
  • C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。

Code:

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    int romanToInt(string s) {
        int ans = 0;
        for(int i = 0; i < s.length(); i++) {
            if (s[ i ] == 'I' && s[ i + 1] == 'V') {
                ans += 4;
                i++;
            }
            else if (s[ i ] == 'I' && s[ i + 1] == 'X') {
                ans += 9;
                i++;
            }
            else if (s[ i ] == 'X' && s[ i + 1] == 'L') {
                ans += 40;
                i++;
            }
            else if (s[ i ] == 'X' && s[ i + 1] == 'C') {
                ans += 90;
                i++;
            }
            else if (s[ i ] == 'C' && s[ i + 1] == 'D') {
                ans += 400;
                i++;
            }
            else if (s[ i ] == 'C' && s[ i + 1] == 'M') {
                ans += 900;
                i++;
            }
            else if (s[ i ] == 'I') {
                ans += 1;
            }
            else if (s[ i ] == 'V') {
                ans += 5;
            }
            else if (s[ i ] == 'X') {
                ans += 10;
            }
            else if (s[ i ] == 'L') {
                ans += 50;
            }
            else if (s[ i ] == 'C') {
                ans += 100;
            }
            else if (s[ i ] == 'D') {
                ans += 500;
            }
            else if (s[ i ] == 'M') {
                ans += 1000;
            }
        }
        return ans;
    }
};

int main() {
    Solution solution;
    string string1;
    int result;
    cin >> string1;
    result = solution.romanToInt(string1);
    cout<< result << endl;
    return 0;
}