forked from tejas-2232/Algorithmic_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoman to Integer Converter
More file actions
35 lines (30 loc) · 846 Bytes
/
Roman to Integer Converter
File metadata and controls
35 lines (30 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Function to convert Roman numeral to integer
function romanToInt(s) {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let total = 0;
for (let i = 0; i < s.length; i++) {
const current = romanMap[s[i]];
const next = romanMap[s[i + 1]];
// If the next numeral is larger, subtract current value
if (next && current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}
// Example usage
console.log(romanToInt("III")); // Output: 3
console.log(romanToInt("IV")); // Output: 4
console.log(romanToInt("IX")); // Output: 9
console.log(romanToInt("LVIII")); // Output: 58
console.log(romanToInt("MCMXCIV"));// Output: 1994