13. Roman to Integer

题目链接:https://leetcode.com/problems/roman-to-integer/

 

解题思路:

题目意思是要把罗马符号转为数字,问题就是4和9等数字,要额外注意,除此之外都是累加上去的。

所以要判断是否是4,或者9,从后往前判断,如果这个字符等于“I”且这个数小于5,说明代表的是1;但如果这个数大于5,说明代表的I在左边。

 

 1 public static int romanToInt(String s) {
 2     int res = 0;
 3     for (int i = s.length() - 1; i >= 0; i--) {
 4         char c = s.charAt(i);
 5         if(c == 'I'){
 6             if(res >= 5)//如果>=5, 说明之前肯定遍历过V了,所以这个I肯定在左边,减
 7                 res += -1;
 8             else
 9                 res += 1;
10         }else if(c == 'V'){//遇见V,L,D,M,统统都加5,50,500,100
11             res += 5;
12         }else if(c == 'X'){
13             if(res >= 50)//说明肯定之前有过L,这个X肯定在左边,减
14                 res += -10;
15             else 
16                 res += 10;
17         }else if(c == 'L'){
18             res += 50;
19         }else if(c == 'C'){//说明之前有D,这个C肯定在左边,减。能被减的只有I X C
20             if(res >= 500)
21                 res += -100;
22             else
23                 res += 100;
24         }else if(c == 'D'){
25             res += 500;
26         }else if(c == 'M'){
27             res += 1000;
28         }
29     }
30     return res;
31 }

 

posted @ 2019-05-07 20:19  王爷爱吃秋刀鱼  阅读(111)  评论(0编辑  收藏  举报