Sunday, June 13, 2021

Javascript Practice 78: JS Hero - Roman numerals II

 
Question: 

Write a function roman that converts an Arabic number (up to 1000) into a Roman numeral.

Example: roman(483) should return 'CDLXXXIII'.




Answer: 

function roman (n) {

let romanObj = {

M: 1000, 
CM: 900, 
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1

};

let roman2 = ''; 

for (let key in romanObj) {

while (n >= romanObj[key]) {

roman2 += key;
n -= romanObj[key]; 

}
}
return roman2; 
}; 





> we declare a function 'roman'
> it has one parameter 'n'
> we declare a variable ‘romanObj’ 
> we initialize it with roman numerals and their values in ‘key: value’ format
> like this: {I:1, V:5, X:10, etc}
> thus we make the variable ‘romanObj’ an object; that holds multiple values in terms of properties and methods
> we declare another variable ‘roman2’ and it is an empty string
> we leave it empty as we shall initialize it later by adding the roman version of the integers and then return it later
> we first use the ‘for in loop’ to loop through every key value pair of the ‘romanObj’ object
> to access the key; we can log the key or console.log(‘key: ‘, key) / console.log(key)
> to access the value; we can log the value or console.log(‘value: ‘, romanObj[key]) / console.log(romanObj[key])
> inside this ‘for in loop’ we run another ‘while loop’ 
> so while our number ‘n’ is greater than or equal to the value or romanObj[key], then in that case we want to add the value to roman2; our value will be the key
> like this: roman2 += key
> every time a key is added to the ‘roman2’ variable we also need to subtract that key value from our number ‘n’
> like this: n -= romanObj[key]
> so the while loop iteration keeps looping till our number ‘n’ is less than romanObj[key] or the key value
> the while loop stops when ‘n’ is less than romanObj[key] or the key value
> after that the outer ‘for in loop’ stops 
> and then we can return roman2

No comments:

Post a Comment