[leetcode] Roman to Integer


Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

tag: math, string

9/28/2015 update

class Solution {
public:
    unordered_map<char, int> map;
    int romanToInt(string s) {
        map['I'] = 1;
        map['V'] = 5;
        map['X'] = 10;
        map['L'] = 50;
        map['C'] = 100;
        map['D'] = 500;
        map['M'] = 1000;
        int prev = 1000;
        int ans = 0;
        for(int i = 0; i < s.size(); i++){
            int v = map[s[i]];
            if(prev < v){
                ans = ans - 2 * prev + v;
            }
            else{
                ans = ans + v;
            }
            prev = v;
        }
        return ans;
    }
};

 

简单题,但是我算了好久。

1. switch只能switch数字或字符;

2. 先判断token是否为2位长度,然后再判断一位。否则会出错。

class Solution {
public:
    string symbol[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    int value[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    int romanToInt(string s) {
        int idx = 0;
        int result = 0;
        while(idx < s.size()){
            int i = getIndex(s, idx);
            result += value[i];
        }
        return result;
    }
    int getIndex(string s, int& idx){
        string ss = s.substr(idx, 2);
        for(int i = 0; i < 13; i++){
            if(ss == symbol[i]){
                idx +=2;
                return i;
            }
        }
        ss = s.substr(idx, 1);
        for(int i = 0; i < 13; i++){
            if(ss == symbol[i]){
                idx += 1;
                return i;
            }
        }
    }
};

Selection_016

 

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.