首页 > 其他 > 详细

13. Roman to Integer

时间:2017-07-17 21:22:19      阅读:273      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!