Roman to Integer

来源:互联网 发布:阿里云搭建视频教程 编辑:程序博客网 时间:2024/05/01 17:55

题目

Given a roman numeral, convert it to an integer.

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


解题思路

组成罗马数字的字符一共有7个,均是大写的。I=1,V=5,X=10,L=50,C=100,D=500,M=1000

出现一次加一次它们代表的值。需要注意的是:当出现IV,IX时,加上I的负值;出现XL,XC时,加上X的负值;

出现CD,CM时,加上C的负值。


代码

public class Solution {    public int romanToInt(String s){int sum=0;for(int i=0;i<s.length();++i)switch(s.charAt(i)){case 'I': if(i+1<s.length()&&(s.charAt(i+1)=='V'||s.charAt(i+1)=='X'))  sum-=1;  else  sum+=1;  break;case 'V': sum+=5;  break;case 'X': if(i+1<s.length()&&(s.charAt(i+1)=='L'||s.charAt(i+1)=='C'))  sum-=10;  else  sum+=10;  break;case 'L': sum+=50;  break;case 'C': if(i+1<s.length()&&(s.charAt(i+1)=='D'||s.charAt(i+1)=='M'))  sum-=100;  else  sum+=100;  break;case 'D': sum+=500;break;case 'M': sum+=1000;  break;}return sum;}}

运行结果


0 0
原创粉丝点击