【leetcode】Integer to Roman & Roman to Integer(easy)
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 = 0; int c[108]; c['I'] = 1; c['V'] = 5; c['X'] = 10; c['L'] = 50; c['C'] = 100; c['D'] = 500; c['M'] = 1000; for(int i = 0; i < s.size(); ++i) { if((s[i] == 'I' || s[i] == 'X' || s[i] == 'C') && (i + 1 < s.size() && c[s[i + 1]] > 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(1000, "M")); v.push_back(make_pair(900, "CM")); v.push_back(make_pair(500, "D")); v.push_back(make_pair(400, "CD")); v.push_back(make_pair(100, "C")); v.push_back(make_pair(90, "XC")); v.push_back(make_pair(50, "L")); v.push_back(make_pair(40, "XL")); v.push_back(make_pair(10, "X")); v.push_back(make_pair(9, "IX")); v.push_back(make_pair(5, "V")); v.push_back(make_pair(4, "IV")); v.push_back(make_pair(1, "I")); string roman; for(int i = 0; i < v.size(); ++i) { int n = num / v[i].first; if(((i & 0x1) == 1) && n > 0) { roman += v[i].second; num -= v[i].first; } else if(((i & 0x1) == 0)) { 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/1000)%10]; result += HUNDS[(int)(num/100)%10]; result += TENS[(int)(num/10)%10]; result += ONES[num%10]; 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"};