13. Roman to Integer

Posted hozhangel

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

leetcode上已有的解决方法:

1、https://leetcode.com/problems/roman-to-integer/discuss/

public int romanToInt(String s) {
     int sum=0;
    if(s.indexOf("IV")!=-1){sum-=2;}
    if(s.indexOf("IX")!=-1){sum-=2;}
    if(s.indexOf("XL")!=-1){sum-=20;}
    if(s.indexOf("XC")!=-1){sum-=20;}
    if(s.indexOf("CD")!=-1){sum-=200;}
    if(s.indexOf("CM")!=-1){sum-=200;}
    
    char c[]=s.toCharArray();
    int count=0;
    
   for(;count<=s.length()-1;count++){
       if(c[count]==‘M‘) sum+=1000;
       if(c[count]==‘D‘) sum+=500;
       if(c[count]==‘C‘) sum+=100;
       if(c[count]==‘L‘) sum+=50;
       if(c[count]==‘X‘) sum+=10;
       if(c[count]==‘V‘) sum+=5;
       if(c[count]==‘I‘) sum+=1;
       
   }
   
   return sum;
    
}

 

2、C++用到map https://leetcode.com/problems/roman-to-integer/discuss/

int romanToInt(string s) 
{
    unordered_map<char, int> T = { { I , 1 },
                                   { V , 5 },
                                   { X , 10 },
                                   { L , 50 },
                                   { C , 100 },
                                   { D , 500 },
                                   { M , 1000 } };
                                   
   int sum = T[s.back()];
   for (int i = s.length() - 2; i >= 0; --i) 
   {
       if (T[s[i]] < T[s[i + 1]])
       {
           sum -= T[s[i]];
       }
       else
       {
           sum += T[s[i]];
       }
   }
   
   return sum;
}

 

以上是关于13. Roman to Integer的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 13. Roman to Integer

LeetCode之Easy篇 ——(13)Roman to Integer

「Leetcode」13. Roman to Integer(Java)

LeetCode 13. Roman to Integer

13. Roman to Integer

#Leetcode# 13. Roman to Integer