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.
题意:
给定一个罗马数字,将其转换为整数。
输入数据范围从1到3999
题解:
根据规则,左减的数字有限制,仅限于I、X、C,且最多一位,该位小于其右侧的数字,
则只有在s[i] < s[i + 1]时才减去s[i]对应的值,否则加上s[i]对应的值
Code【Java】
public class Solution {
static String str = "IVXLCDM";
static int[] nums = {1, 5, 10, 50, 100, 500, 1000};
public int romanToInt(String s) {
int ans = 0;
for (int i = 0; i < s.length() - 1; ++i) {
int index = str.indexOf(s.charAt(i));
int index2= str.indexOf(s.charAt(i + 1));
ans += (index < index2) ? -nums[index] : nums[index];
}
ans += nums[str.indexOf(s.charAt(s.length() - 1))];
return ans;
}
}
Code【C++】
class Solution {
string str = "IVXLCDM";
int nums[7] = {1, 5, 10, 50, 100, 500, 1000};
public:
int romanToInt(string s) {
int ans = 0;
for (int i = 0; i < s.length() - 1; ++i) {
int index = str.find(s[i]);
int index2= str.find(s[i + 1]);
ans += (index < index2) ? -nums[index] : nums[index];
}
ans += nums[str.find(s[s.length() - 1])];
return ans;
}
};