Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Roman to Integer - Leetcode 13.js - Invalid Roman Numeric Value Test Case #29

Open
@maheshmuttintidev

Description

I found that this solution doesn't handle the "Invalid Roman Numeric Value".

Ex: If we pass IIXX, The output is 20 which is wrong since the IIXX is invalid roman number. In this case, we throw an error, rest of the code continues..

Here is my js solution:

function romanToInt(s) {
 const d = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000};
 let summ = 0;
 const n = s.length;
 let i = 0;
 while (i < n) {
 if(i > 1 && d[s[i - 2]] < d[s[i - 1]] && d[s[i]] <= d[s[i - 1]]) {
 throw new Error(`Invalid Roman numeric sequence ${s}`);
 }
 if (i < n - 1 && d[s[i]] < d[s[i + 1]]) {
 summ += d[s[i + 1]] - d[s[i]];
 i += 2;
 } else {
 summ += d[s[i]];
 i++;
 }
 }
 return summ;
}
console.log(romanToInt('IIXX'));
console.log(romanToInt('MMD'));

Note

It would be helpful if you add the example test cases when you have the solution for the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /