首页 > 其他 > 详细

LeetCode 13 Roman to Integer(罗马数到整型数)

时间:2015-10-15 18:44:42      阅读:225      评论:0      收藏:0      [点我收藏+]

翻译

给定一个罗马数字,将其转换到整型数值。

输入被保证在1到3999之间。

原文

Given a roman numeral, convert it to an integer.

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

一开始就没有构思好,虽然按上一题的套路可以走下去,但结果就是像我下面这样……代码凌乱……

public class Solution
{
    public int RomanToInt(string s)
    {
        int result = 0;
        Type R = typeof(Roman);
        string first, second;
        if (s.Length > 1)
        {
            first = s.Substring(0, 1); second = s.Substring(0, 2);
        }
        else
        {
            first = s.Substring(0, 1); second = "";
        }
        foreach (var r in Enum.GetNames(R).Reverse())
        {
            while ((r.Length == 1 && first == r) || (r.Length == 2 && second == r))
            {
                result += int.Parse(Enum.Format(R, Enum.Parse(R, r), "d"));
                int lenR = r.Length, lenS = s.Length;
                if (lenS - lenR < 1)
                    s = "";
                else
                    s = s.Substring(lenR, lenS - lenR);

                if (s.Length > 1)
                {
                    first = s.Substring(0, 1); second = s.Substring(0, 2);
                }
                else if (s.Length == 1)
                {
                    first = s.Substring(0, 1); second = "";
                }
                else
                {
                    first = ""; second = "";
                }
            }
        }
        return result;
    }

}

public enum Roman
{
    M = 1000,
    CM = 900,
    D = 500,
    CD = 400,
    C = 100,
    XC = 90,
    L = 50,
    XL = 40,
    X = 10,
    IX = 9,
    V = 5,
    IV = 4,
    I = 1
};

虽然吧,可以运行……但是效率也太低了,简直不忍直视……于是还是像其他大神学习学习……

下面这段代码深深的打动了我……数组作为数组的索引……我最不常用的用法了……

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> map = {{‘I‘, 1}, {‘V‘, 5}, {‘X‘, 10}, {‘L‘, 50}, {‘C‘, 100}, {‘D‘, 500}, {‘M‘, 1000}};
        int ret = 0;
        for (int idx = 0; idx < s.size(); ++idx) {
            if ((idx < s.size()-1) && (map[s[idx]] < map[s[idx+1]])) {
                ret -= m[s[idx]];
            }
            else {
                ret += m[s[idx]];
            }
        }
        return ret;
    }
};

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp

LeetCode 13 Roman to Integer(罗马数到整型数)

原文:http://blog.csdn.net/nomasp/article/details/49154161

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