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

13_Roman to Integer

时间:2016-01-13 15:50:20      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

Given a roman numeral, convert it to an integer.

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

 

罗马数字转化为阿拉伯数字

I  1

X  10

C  100

M  1000

V  5

L  50  

D  500

 

小数字在大数字前,则为大数字减去小数字,小数字在大数字后,则为大数字加小数字

 

public class Solution {
    public int RomanToInt(string s) {
        int result = 0;
            char[] chList = s.ToCharArray();

            Dictionary<char, int> romaDic = new Dictionary<char,int>();
            romaDic.Add(I, 1);
            romaDic.Add(X, 10);
            romaDic.Add(C, 100);
            romaDic.Add(M, 1000);
            romaDic.Add(V, 5);
            romaDic.Add(L, 50);
            romaDic.Add(D, 500);

            int former, latter = 0;
            for (int i = 0; i < chList.Length - 1; i++)
            {
                former = 0;
                latter = 0;
                
                romaDic.TryGetValue(chList[i], out former);
                romaDic.TryGetValue(chList[i + 1], out latter);
                if (former < latter)
                {
                    result -= former;
                }
                else 
                {
                    result += former;
                }
            }
            
            int last = 0;
            romaDic.TryGetValue(chList.Last(), out last);
            result += last;

            return result;
    }
}

 

13_Roman to Integer

标签:

原文地址:http://www.cnblogs.com/Anthony-Wang/p/5127349.html

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