码迷,mamicode.com
首页 > 其他好文 > 详细

13. Roman to Integer

时间:2017-07-17 22:14:15      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:ret   integer   convert   ecc   输出   罗马数字   pre   roman   判断   

Given a roman numeral, convert it to an integer.

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

 

给出罗马数字 输出对应的阿拉伯数字。思路来自29的罗马数字

观看罗马数字构造规则(http://www.jianshu.com/p/0ecc70f62bb7)我们可以发现相邻的两个字符 如果第一个比第二个大 那么第二个字符要么和第三个字符组成(10-1,100-10等组合)要么就是末尾的字符。而第一个字符只要把他带代表的阿拉伯数字加上就可以了。第二个字符可以根据下标i判断是不是末尾字符。

class Solution {
public:
    int get(char c) {
        if (c == I) return 1;
        else if (c == V) return 5;
        else if (c == X) return 10;
        else if (c == L) return 50;
        else if (c == C) return 100;
        else if (c == D) return 500;
        else if (c == M) return 1000;
    }
    int romanToInt(string s) {
        if (s.size() == 1) return get(s[0]);
        int sum = 0;
        int mark = 0;
        for (int i = 0; i < s.size() - 1; ++i) {
            int x = get(s[i]);
            int y = get(s[i + 1]);
            //cout << x << " "<< y<<endl;
            if (x < y) {
                sum += y - x,++i; 
                if (i == s.size() - 2) mark = get(s[s.size() - 1]);
            }
            else {
                sum += x;
                if (i == s.size() - 2) mark = y;
            }
        }
        return sum + mark;
    }
};

 

13. Roman to Integer

标签:ret   integer   convert   ecc   输出   罗马数字   pre   roman   判断   

原文地址:http://www.cnblogs.com/pk28/p/7197185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!