Created
May 19, 2020 17:21
-
-
Save ObsidianCat/977e4fca6c28cc7f298decb207ad39f4 to your computer and use it in GitHub Desktop.
2 algorithms - Conversion of roman number to integer and integer to roman number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
var romanToInt = function(s) { | |
let result = 0 | |
const conversion = { | |
"I": 1, | |
"V": 5, | |
"X": 10, | |
"L": 50, | |
"C": 100, | |
"D": 500, | |
"M": 1000 | |
} | |
for(let i =s.length-1; i >= 0; i--){ | |
const curNum = conversion[s.charAt(i)] | |
if(i === s.length-1){ | |
result += curNum | |
continue; | |
} | |
const prevNum = conversion[s.charAt(i+1)] | |
if(curNum < prevNum){ | |
result -= curNum | |
} else { | |
result +=curNum | |
} | |
} | |
return result | |
}; | |
/** | |
* @param {number} num | |
* @return {string} | |
*/ | |
var intToRoman = function(num) { | |
const conversion = { | |
1: "I", | |
4: "IV", | |
5: "V", | |
9: "IX", | |
10: "X", | |
40: "XL", | |
50: "L", | |
90: "XC", | |
100: "C", | |
400: "CD", | |
500: "D", | |
900: "CM", | |
1000: "M" | |
} | |
const options = [1000, 900, 500, 400, 100, 90, 50, 40, 10,9, 5,4, 1] | |
let result = "" | |
let step = 0 | |
while(num > 0){ | |
let curStep = options[step] | |
if(curStep > num){ | |
step++ | |
continue | |
} | |
const times = Math.floor(num/curStep); | |
result += conversion[curStep].repeat(times) | |
num = num - (curStep*times) | |
step++ | |
} | |
return result | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment