王廷瑋|數位醫療|智慧醫療: 13. Roman to Integer WFU

2024年7月2日 星期二

13. Roman to Integer

13. Roman to Integer


羅馬數字由七個不同的符號表示:I、V、X、L、C、D 和 M。

符號 值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000

例如,數字 2 用羅馬數字寫作 II,就是兩個一相加。數字 12 用羅馬數字寫作 XII,即 X + II。數字 27 用羅馬數字寫作 XXVII,即 XX + V + II。

羅馬數字通常從左到右按從大到小的順序書寫。然而,數字 4 不是寫作 IIII,而是寫作 IV。因為 1 在 5 前面,所以我們將其減去,得到 4。同樣的原理適用於數字 9,寫作 IX。有六種情況下會使用減法:

I 可以放在 V(5)和 X(10)之前來表示 4 和 9。 X 可以放在 L(50)和 C(100)之前來表示 40 和 90。 C 可以放在 D(500)和 M(1000)之前來表示 400 和 900。

給定一個羅馬數字,將其轉換為整數。

範例 1:

輸入:s = "III" 輸出:3 解釋:III = 3。


Python


class Solution:
def romanToInt(self, s: str) -> int:
# Define the mapping of Roman numerals to integers
roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Initialize the result integer
result = 0
# Iterate through the string
for i in range(len(s)):
# If the current value is less than the next value, subtract it
if i < len(s) - 1 and roman_to_int[s[i]] < roman_to_int[s[i + 1]]:
result -= roman_to_int[s[i]]
# Otherwise, add the current value
else:
result += roman_to_int[s[i]]
return result

16.38MB, 42ms


C++


#include <string>
#include <unordered_map>

using namespace std;

class Solution {
public:
int romanToInt(string s) {
// Define the mapping of Roman numerals to integers
unordered_map<char, int> roman_to_int = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
// Initialize the result integer
int result = 0;
// Iterate through the string
for (int i = 0; i < s.size(); ++i) {
// If the current value is less than the next value, subtract it
if (i < s.size() - 1 && roman_to_int[s[i]] < roman_to_int[s[i + 1]]) {
result -= roman_to_int[s[i]];
}
// Otherwise, add the current value
else {
result += roman_to_int[s[i]];
}
}
return result;
}
};

12.76MB, 7ms


Javascript


/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
// Define the mapping of Roman numerals to integers
const romanToIntMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
// Initialize the result integer
let result = 0;
// Iterate through the string
for (let i = 0; i < s.length; i++) {
// If the current value is less than the next value, subtract it
if (i < s.length - 1 && romanToIntMap[s[i]] < romanToIntMap[s[i + 1]]) {
result -= romanToIntMap[s[i]];
}
// Otherwise, add the current value
else {
result += romanToIntMap[s[i]];
}
}
return result;
};

54.84MB, 111ms