These problems appeared in leecode and featured in various blogs, i have just summarised and included them using ts-problems deck.
๐ Roman Numerals to Integer conversion
Numbers generally increase in a roman numeral notation from right to left, any subtractive number must also be smaller than our current res
.
So we can avoid the need for an extra variable here. We do run into the case of repeated numerals causing an issue III
, but we can clear that by multiplying num
by any number between 2 and 4 before comparing it to res
, since the numerals jump in value by 5x.
Once we know how to properly identify a subtractive numeral, it's a simple matter to just iterate in reverse through given numeral to find and return the res
.
function romanToInt(s: string): number {
let res: number = 0;
const symbols = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
s.split("")
.reverse()
.forEach((char) => {
let val: number = parseInt(symbols[char]);
if (res > 4 * val) {
res -= val;
} else {
res += val;
}
});
return res;
}
๐ Integer to Roman Numerals conversion
This solution uses a lookup table composed which can help in easier conversion and much simple compared to the above one.
function intToRoman(num: number): string {
let res:string = "";
const value:number [] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const numerals:string [] = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
for (let i = 0; num; i++)
while (num >= value[i]){
res += numerals[i];
num -= value[i];
}
return res;
}
Here I have tried to solve them in typescript using ts-problems repo.
๐ original post at ๐ Dev Post
Thanks for supporting! ๐
Would be really great if you like to โ Buy Me a Coffee, to help boost my efforts.
Top comments (0)