Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
maheshmuttintidev opened this issue Jan 28, 2025 · 0 comments

Comments

@maheshmuttintidev
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant