Posts Roman Number to Integer (geeksforgeeks - SDE Sheet)
Post
Cancel

Roman Number to Integer (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

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.

1
2
3
4
5
6
7
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {

    public int romanToDecimal(String str) {

        int n = str.length();

        // store Roman numerals and their corresponding integer values
        Map<String, Integer> map = new HashMap<>();

        map.put("I", 1);
        map.put("V", 5);
        map.put("X", 10);
        map.put("L", 50);
        map.put("C", 100);
        map.put("D", 500);
        map.put("M", 1000);

        int total = 0;

        for (int i = 0; i < n; i++) {

            // If the current character is the last one in the string
            if (i == n - 1) {

                // add its corresponding value
                String current = String.valueOf(str.charAt(i));
                total += map.get(current);

            // If the current character is not the last one
            // Compare it with the value for next character
            } else {

                String current = String.valueOf(str.charAt(i));
                String next = String.valueOf(str.charAt(i + 1));

                // Check if the current numeral is less than the next numeral
                // We need to subtract the current value from total
                if (map.get(current) < map.get(next)) {
                    total -= map.get(current);
                // Otherwise the value can be added
                } else {
                    total += map.get(current);
                }

            }

        }

        return total;

    }

}
This post is licensed under CC BY 4.0 by the author.