[LeetCode] 13. Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Thought process:
Iterate the numeral. Add every character together and subtract the special cases (e.g. IV). There is going to be at most one occurrence of each special case.

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
class Solution {
    public int romanToInt(String s) {
        int sum = 0;
        for (char c : s.toCharArray()) {
            switch (c) {
                case 'I':
                    sum++;
                    break;
                case 'V':
                    sum += 5;
                    break;
                case 'X':
                    sum += 10;
                    break;
                case 'L':
                    sum += 50;
                    break;
                case 'C':
                    sum += 100;
                    break;
                case 'D':
                    sum += 500;
                    break;
                case 'M':
                    sum += 1000;
                    break;
            }
        }
        
        if (s.indexOf("IV") != -1 || s.indexOf("IX") != -1) {
            sum -= 2;
        }
        if (s.indexOf("XL") != -1 || s.indexOf("XC") != -1) {
            sum -= 20;
        }
        if (s.indexOf("CD") != -1 || s.indexOf("CM") != -1) {
            sum -= 200;
        }
        
        return sum;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary