zoukankan      html  css  js  c++  java
  • 13_Roman to Integer

    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;
        }
    }
  • 相关阅读:
    RF用户关键字
    RF循环分支
    RF使用
    RF变量
    RF介绍
    元件作用域
    元件介绍
    工作总结之测试
    港股通Level2介绍
    linux中配置yum源
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5127349.html
Copyright © 2011-2022 走看看