Leet - 13

Having fun on Leetcode with C++, Java, Python & GO

Problem 13. Roman to Integer

My attempt(s)

Code

C++

 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
class Solution {
public:
    
    int romanToDigit(char s){
        switch(s)
        {
            case 'I':
                return 1;
                break;
            case 'V':
                return 5;
                break;
            case 'X':
                return 10;
                break;
            case 'L':
                return 50;
                break;
            case 'C':
                return 100;
                break;
            case 'D':
                return 500;
                break;
            case 'M':
                return 1000;
                break;
        }
        return 0;
    }
    
    int romanToInt(string s) {
        int store=0;
        int last=0;
        int temp=0;
        for (int i=0;i<s.length();i++)
        {
            temp=romanToDigit(s[i]);
            store=store+temp;
            if (temp>last)
                store=store-2*last;
            last=temp;
        }
        return store;
    }

};

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0