代码改变世界

13_Roman to Integer

2016-01-13 15:05  FTD_W  阅读(176)  评论(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;
    }
}