Skip to content

Commit 01ffe74

Browse files
committed
roman to int
1 parent 64b8bf7 commit 01ffe74

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Roman to integer/romanToInt.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// PSEUDOCODE
2+
3+
/**
4+
*
5+
* create a hash map with the value of each synol in the roman numeral
6+
* initiale the result number with 0
7+
* iterate the roman string
8+
* check the current string value in the hash if its less than the next character value
9+
* if its less than the next, subtract it from the next character. (case of IV)
10+
*
11+
*/
12+
13+
var romanToInt = function (s) {
14+
const romanHash = {
15+
'I': 1,
16+
'V': 5,
17+
'X': 10,
18+
'L': 50,
19+
'C': 100,
20+
'D': 500,
21+
'M': 1000,
22+
};
23+
24+
let result = 0;
25+
26+
for(let i = 0, len = s.length; i < len; i++) {
27+
const currentVal = romanHash[s[i]];
28+
const nextCharVal = romanHash[s[i + 1]];
29+
30+
if(currentVal < nextCharVal) {
31+
result += nextCharVal - currentVal;
32+
i++
33+
}else{
34+
result += currentVal;
35+
}
36+
}
37+
38+
return result;
39+
}

0 commit comments

Comments
 (0)