Roman to Integer

Roman to Integer


Problem Statement

Given a string in roman no format(s) your task is to convert it to an integer. Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Example 1

Input :
s = V

Output : 5

Example 2

Input :
s = III 

Output : 3

Task

Complete the function romanToDecimal() which takes a string as input parameter and returns the equivalent decimal number.

Expected Time Complexity : O(|S|); |S| = length of string S.
Expected Auxiliary Space : O(1).

Constraints :
1 <= Roman number range <= 3999



Solutions

Java Solution


class Solution {
    // Finds decimal value of a given roman numeral
    public int romanToDecimal(String str) {
        // code here
        int res = 0;
        for(int i=0; i<str.length(); i++) {
            int str1 = value(str.charAt(i));
            if(i+1 < str.length()) {
                int str2 = value(str.charAt(i+1));
                if(str1 >= str2) {
                    res = res + str1;
                }
                else {
                    res = res + str2 - str1;
                    i++;
                }
            }
            else {
                res = res + str1;
            }
        }
        return res;
    }
        
    static int value(char c) {
        if(c == 'I') {
            return 1;
        }
        if(c == 'V') {
            return 5;
        }
        if(c == 'X') {
            return 10;
        }
        if(c == 'L') {
            return 50;
        }
        if(c == 'C') {
            return 100;
        }
        if(c == 'D') {
            return 500;
        }
        if(c == 'M') {
            return 1000;
        }
        return -1;
    }
}     
    

Post a Comment

0 Comments