TypechoJoeTheme

IT技术分享

统计

[LeetCode 13] Roman to Integer [C++]

2017-06-05
/
0 评论
/
628 阅读
/
正在检测是否收录...
06/05

1. Description

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

2. Example

input s = "XXIII"
output 23

3. Code

int romanToInt(string s) {
    static unordered_map<char, int> map = {
        { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 }
    };

    int sum = map[s.back()];

    for (int i = 0; i < s.length() - 1; i++) {
        sum = map[s[i]] < map[s[i + 1]] ? sum - map[s[i]] : sum + map[s[i]];
    }
    return sum;
}

4.Test

#include<iostream>
#include<string>
#include<unordered_map>

using namespace std;

class LeetCode13 {
public:
    int romanToInt(string s) {
        static unordered_map<char, int> map = {
            { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 }
        };

        int sum = map[s.back()];

        for (int i = 0; i < s.length() - 1; i++) {
            sum = map[s[i]] < map[s[i + 1]] ? sum - map[s[i]] : sum + map[s[i]];
        }
        return sum;
    }
};

int main() {
    LeetCode13 leetCode13;
    cout << leetCode13.romanToInt("MMMCMXCIX") << endl;
    system("pause");
    return 0;
}

5. Submission Details

6. Runtime Distribution

Digital
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/317/(转载时请注明本文出处及文章链接)