![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript algorithm for converting Roman numbers to decimal numbers
We are required to write a function that takes in a string of roman number and returns its decimal (base 10) equivalent. Therefore, let’s write the code for this function −
Example
const romanToInt = (s) => { const legend = "IVXLCDM"; const l=[1,5,10,50,100,500,1000]; let sum=0; while(s){ if(!!s[1] && legend.indexOf(s[0]) < legend.indexOf(s[1])){ sum += (l[legend.indexOf(s[1])] - l[legend.indexOf(s[0])]); s = s.substring(2, s.length); } else { sum += l[legend.indexOf(s[0])]; s = s.substring(1, s.length); } } return sum; }; console.log(romanToInt('CLXXVIII')); console.log(romanToInt('LXXXIX')); console.log(romanToInt('LV')); console.log(romanToInt('MDLV'));
Output
The output in the console will be −
178 89 55 1555
Advertisements