Roman to Integer

Given a roman numeral, convert it to an integer.

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

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         if(s.length()<=0) return 0;
 4         int res = 0;
 5         for(int i=0;i<s.length();i++){
 6             int cur = get(s.charAt(i));
 7             if(i>0 && get(s.charAt(i-1))<cur)
 8                 res += cur-2*get(s.charAt(i-1));
 9             else{
10                 res +=cur;
11             }
12         }
13         return res;
14     }
15     public int get(char c){
16         if(c=='I') return 1;
17         if(c=='V') return 5;
18         if(c=='X') return 10;
19         if(c=='L') return 50;
20         if(c=='C') return 100;
21         if(c=='D') return 500;
22         if(c=='M') return 1000;
23         return 0;
24     }
25 }
View Code

 

posted @ 2014-02-06 05:03  krunning  阅读(96)  评论(0编辑  收藏  举报