Created
June 28, 2021 16:24
-
-
Save kishork2120/4abbd42488be554fbe57b4feef2c94ff to your computer and use it in GitHub Desktop.
Integer to Roman - leetcode solution
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
function intToRoman(num: number): string { | |
let result = ''; | |
let programInput = num; | |
const staticValues = { | |
1:'I', | |
2:'II', | |
3:'III', | |
4:'IV', | |
5:'V', | |
10:'X', | |
50:'L', | |
100:'C', | |
500:'D', | |
1000:'M', | |
9:'IX', | |
40:'XL', | |
90:'XC', | |
400:'CD', | |
900:'CM' | |
} | |
let inputLength = programInput.toString().length; | |
const ranges = [...Object.keys(staticValues).map((d)=>parseInt(d)),Infinity]; | |
while(inputLength--){ | |
let temp = programInput%(Math.pow(10,inputLength)); | |
if(programInput-temp) rangeCalculator(programInput-temp); | |
programInput = temp; | |
} | |
function rangeCalculator(input){ | |
let range; | |
for(let i=0;i<ranges.length;i++){ | |
if(input<ranges[i]){ | |
range = ranges[i-1]; | |
break; | |
} | |
} | |
if(input%range === 0){ | |
result += new Array(input/range).fill(staticValues[range]).join(''); | |
}else{ | |
result += staticValues[range]; | |
return rangeCalculator(input-range) | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment