每日一练之Roman to integer & integer to Roman【LeetCode No.12,13】
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
class Solution {
public:
string intToRoman(int num) {
string table[4][10] = {{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
};
string result;
int count = 0;
while(num > 0){
int temp = num % 10;
result = table[count][temp] + result;
num /= 10;
count++;
}
return result;
}
};
Roman to Integer
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
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int> T={
{'I',1},{'V',5},{'X',10},{ 'L' , 50 },{ 'C' , 100 },{ 'D' , 500 },{ 'M' , 1000 }
};
int sum=T[s.back()];
for(int i=s.length()-2;i>=0;--i)
{
if(T[s[i]]<T[s[i+1]]){sum-=T[s[i]];}
else {sum+=T[s[i]];}
}
return sum;
}
};
其实只要明白罗马数字和阿拉伯数字之间的转换关系,这两题还是不难的。