-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathromanToInteger.js
More file actions
32 lines (27 loc) · 859 Bytes
/
Copy pathromanToInteger.js
File metadata and controls
32 lines (27 loc) · 859 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
// Implement a function that converts a Roman numeral to an integer. The function should take a Roman numeral string (e.g., "IX" or "XXI") as input and return the corresponding integer value.
const romanToInteger = (roman) => {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
};
let result = 0;
const length = roman.length;
for (let i = 0; i < length; i++) {
const currentCharValue = romanMap[roman[i]];
const nextCharValue = romanMap[roman[i + 1]];
if (i < length - 1 && currentCharValue < nextCharValue) {
result -= currentCharValue;
} else {
result += currentCharValue;
}
}
return result;
};
const str = 'MV';
const result = romanToInteger(str);
console.log(result);