Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
和上一篇文章相反,这个题是把罗马数字转换成阿拉伯数字,罗马数字十分好处理,如果两个数字是降序的,即可正常相加;
如果两个数字是升序的,那么代表要用大的数字减去小的数字。
public class Solution {
public int romanToInt(String s) {
int len = s.length();
int []num = new int[len];
int ans = 0;
for(int i=0;i<len;i++){
if(s.charAt(i)=='I'){
num[i] = 1;
}
else if(s.charAt(i)=='V'){
num[i] = 5;
}
else if(s.charAt(i)=='X'){
num[i] = 10;
}
else if(s.charAt(i)=='L'){
num[i] = 50;
}
else if(s.charAt(i)=='C'){
num[i] = 100;
}
else if(s.charAt(i)=='D'){
num[i] = 500;
}
else if(s.charAt(i)=='M'){
num[i] = 1000;
}
}
for(int j=0;j<len;j++){
if(j!=len-1&&num[j]<num[j+1]){
ans += (num[j+1]-num[j]);
j++;
}
else ans += num[j];
}
return ans;
}
}
本文介绍了一种将罗马数字转换为整数的算法实现。通过解析罗马数字的构成规律,该算法能正确处理从1到3999范围内的罗马数字。对于连续递增的罗马数字采用减法原则,反之则进行加法运算。
658

被折叠的 条评论
为什么被折叠?



