No.013 Roman to Integer

2018-02-27 15:38:58 浏览数 (1)

13. Roman to Integer

  • Total Accepted: 95998
  • Total Submissions: 234087
  • Difficulty: Easy

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

  思路:

  根据上一篇的关于罗马数字的解释,我们可以知道,在罗马数字中左减右加的原则,所以当较小的数在较大的数前面时,表示是相减的,所以此题就显得很简单了

代码语言:javascript复制
 1 public int romanToInt(String s) {
 2     
 3     char [] arr = s.trim().toCharArray() ;
 4     int res = toNumber(arr[0]) ;
 5     for(int i = 1 ; i < arr.length ; i  ){
 6         if(toNumber(arr[i-1]) < toNumber(arr[i])){
 7             res  = toNumber(arr[i]) - 2*toNumber(arr[i-1]) ;
 8         }else{
 9             res  = toNumber(arr[i]) ;
10         }    
11     }
12     return res ;    
13          
14 }
15 
16 private int toNumber(char ch) {
17     switch (ch) {
18     case 'I':
19         return 1;
20     case 'V':
21         return 5;
22     case 'X':
23         return 10;
24     case 'L':
25         return 50;
26     case 'C':
27         return 100;
28     case 'D':
29         return 500;
30     case 'M':
31         return 1000;
32     }
33     return 0;
34 }

0 人点赞