DEV Community

Debesh P.
Debesh P.

Posted on

13. Roman to Integer | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/roman-to-integer/


leetcode 13


Solution

class Solution {
    public int romanToInt(String s) {
        int n = s.length(); // length of string
        int sum = 0;
        for (int i = 0; i < n; i++) {
            char ch1 = s.charAt(i);
            if ((i + 1) < n && getVal(ch1) < getVal(s.charAt(i + 1))) {
                sum = sum - getVal(ch1);
            } else {
                sum = sum + getVal(ch1);
            }
        }

        return sum;
    }

    public int getVal(char ch) { // values of all roman numerals
        switch (ch) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
            default:
                return 0;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)