C# solution


  • 0
    S
    public class Solution {
    public int RomanToInt(string s) {
        Hashtable has=new Hashtable();//创建哈希表;
        has.Add('I',1);//键为罗马数字,值为对应阿拉伯数字
        has.Add('V',5);
        has.Add('X',10);
        has.Add('L',50);
        has.Add('C',100);
        has.Add('D',500);
        has.Add('M',1000);
        int i=s.Length-1;//字符串长度
        int num=0;
        int pre=0;//之前数值
        int now=0;//当前数值
        while(i>-1)
        {   
            now=(int)has[char.ToUpper(s[i])];//获取对应罗马数字的阿拉伯数字
            num=num+(now>=pre?now:-now);//从右到左到判断并相加
            pre=now;
            i--;
        }
        return num;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.