您的位置:首页 > 编程语言 > Java开发

Roman to Integer leetcode java

2014-08-02 09:01 351 查看
题目

Given a roman numeral, convert it to an integer.

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

题解

这道题跟interger to roman一样都得先熟悉罗马数字的规则。罗马数字的规则我在integer to roman里面写了,可以参考那个。

从后往前检查string,全局维护一个res来记录。

代码如下:

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;
}else if(c == 'V'){//遇见V,L,D,M,统统都加5,50,500,100
res += 5;
}else if(c == 'X'){
if(res >= 50)//说明肯定之前有过L,这个X肯定在左边,减
res += -10;
else
res += 10;
}else if(c == 'L'){
res += 50;
}else if(c == 'C'){//说明之前有D,这个C肯定在左边,减。能被减的只有I X C
if(res >= 500)
res += -100;
else
res += 100;
}else if(c == 'D'){
res += 500;
}else if(c == 'M'){
res += 1000;
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: