Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:首先要学一下罗马数字是怎么表示的,参见百度百科
其实看了上面罗马数字的介绍,可以建一个对应表 把数字和字母对应起来。遇到 I X C且后面字母的数字更大时 减去当前数字,否则加上。
int romanToInt(string s) {
int num = ;
int c[];
c['I'] = ; c['V'] = ; c['X'] = ;
c['L'] = ; c['C'] = ; c['D'] = ; c['M'] = ;
for(int i = ; i < s.size(); ++i)
{
if((s[i] == 'I' || s[i] == 'X' || s[i] == 'C') && (i + < s.size() && c[s[i + ]] > c[s[i]])) //如果当前是I X C 且后面的数字更大 减去当前数字
num -= c[s[i]];
else
num += c[s[i]];
}
return num;
}
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路:还是用到查找表。不过凡是有4或者9的都比较特殊,所以也放在表里,之后查表即可。
string intToRoman(int num) {
vector<pair<int, string>> v;
v.push_back(make_pair(, "M"));
v.push_back(make_pair(, "CM"));
v.push_back(make_pair(, "D"));
v.push_back(make_pair(, "CD"));
v.push_back(make_pair(, "C"));
v.push_back(make_pair(, "XC"));
v.push_back(make_pair(, "L"));
v.push_back(make_pair(, "XL"));
v.push_back(make_pair(, "X"));
v.push_back(make_pair(, "IX"));
v.push_back(make_pair(, "V"));
v.push_back(make_pair(, "IV"));
v.push_back(make_pair(, "I"));
string roman;
for(int i = ; i < v.size(); ++i)
{
int n = num / v[i].first;
if(((i & 0x1) == ) && n > )
{
roman += v[i].second;
num -= v[i].first;
}
else if(((i & 0x1) == ))
{
while(n--)
roman += v[i].second;
num = num % v[i].first;
}
}
return roman;
}
更快的代码,表做的更全,循环都省了:
class Solution {
public:
const static string THOUS[];
const static string HUNDS[];
const static string TENS[];
const static string ONES[];
string intToRoman(int num) {
string result;
result += THOUS[(int)(num/)%];
result += HUNDS[(int)(num/)%];
result += TENS[(int)(num/)%];
result += ONES[num%];
return result;
}
}; const string Solution::THOUS[] = {"","M","MM","MMM"};
const string Solution::HUNDS[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string Solution::TENS[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string Solution::ONES[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};