您的位置:首页 > 其它

leetcode 13. Roman to Integer

2016-06-05 16:22 344 查看
Given a roman numeral, convert it to an integer.

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

与leetcode 12题相反,将罗马数字转换成阿拉伯数字(小于3999)

从前向后遍历如果前面的比后面的小,则加上后面减去前面的值,指针向后移动一位,反之,加上前面的值.

public class A13RomantoInteger {
public int romanToInt(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++) {
int m = valueOfRoman(s.charAt(i));
if(i + 1 < s.length() && m < valueOfRoman(s.charAt(i + 1))) {
ans += valueOfRoman(s.charAt(i + 1)) - m;
i++;
} else {
ans += m;
}
}
return ans;
}
// I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
public int valueOfRoman(char c) {
switch(c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode