Skip to content

Instantly share code, notes, and snippets.

@briansunter
Created October 3, 2020 20:15
Show Gist options
  • Save briansunter/ec7af91065d79a2f790fcd76a2a08a84 to your computer and use it in GitHub Desktop.
Save briansunter/ec7af91065d79a2f790fcd76a2a08a84 to your computer and use it in GitHub Desktop.
Convert Roman Numeral to Integer
/**
Roman to Integer
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/878/
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
// sum so far. add the roman numerals up as we go left to right
let total = 0;
// subtraction rules. certain numbers like I before V are 4 instead of 6
// this is a 'lookup table' where given a number, see which character before it
// requires special handling
const subs = {
V: 'I',
X: 'I',
L: 'X',
C: 'X',
D: 'C',
M: 'C'
}
//lookup table for number to 'normal' integer value
const lookup = {
I:1,
V:5,
X:10,
L:50,
C:100,
D:500,
M:1000
}
//loop over each character, looking at two characters at a time
for (let x = 0; x < s.length; x++){
const fst = s[x];
const snd = s[x+1];
//see if the first character causes the next character to have special handling
if (fst === subs[snd]) {
//if so, add the big number and subtract the small number. ex: IV = 5 - 1
total = total + lookup[snd] - lookup[fst]
//skip ahead so you don't double add
x++
}else if (!snd){
//if you reach the end and there's only one left, just add the only one left
total = total + lookup[fst];
}
else {
//if no special handling needed, just add the single roman numeral normally
// according to the lookup table
total = total + lookup[fst]
}
}
return total;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment