题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
代码:
class Solution {
public:
string intToRoman(int num) {
if ( num< ) return NULL;
const int size = ;
std::string symbol_ori[size] = {"M","D","C","L","X","V","I"};
int value_ori[size] = {,,,,,,};
// gain extra symbol and value pair
std::vector<std::string> symbol_extra;
std::vector<int> value_extra;
for ( int i = ; i < size-; ++i ){
symbol_extra.push_back(symbol_ori[i]);
value_extra.push_back(value_ori[i]);
if ( !(i & ) ){
symbol_extra.push_back(symbol_ori[i+]+symbol_ori[i]);
value_extra.push_back(value_ori[i]-value_ori[i+]);
}
else{
symbol_extra.push_back(symbol_ori[i+]+symbol_ori[i]);
value_extra.push_back(value_ori[i]-value_ori[i+]);
}
}
symbol_extra.push_back(symbol_ori[size-]);
value_extra.push_back(value_ori[size-]); std::string result;
for ( size_t i = ; i < symbol_extra.size(); ++i )
{
int k = num / value_extra[i];
while ( k )
{
result += symbol_extra[i];
k--;
}
num = num % value_extra[i];
}
return result;
}
};
tips:
根据罗马数字进位的特殊规则,预先补上不能正常进位的symbol和value,这样代码可以非常consice
================================================
第二次过这道题,重写一遍加深印象。
class Solution {
public:
string intToRoman(int num) {
if ( num< ) return NULL;
const int size = ;
string symbol_ori[size] = {"M","D","C","L","X","V","I"};
int value_ori[size] = {,,,,,,};
vector<string> symbol_extra;
vector<int> value_extra;
for ( int i=; i<size-; ++i ){
symbol_extra.push_back(symbol_ori[i]);
value_extra.push_back(value_ori[i]);
if ( !( & i) )
{
symbol_extra.push_back(symbol_ori[i+]+symbol_ori[i]);
value_extra.push_back(value_ori[i]-value_ori[i+]);
}
else
{
symbol_extra.push_back(symbol_ori[i+]+symbol_ori[i]);
value_extra.push_back(value_ori[i]-value_ori[i+]);
}
}
symbol_extra.push_back(symbol_ori[size-]);
value_extra.push_back(value_ori[size-]);
string ret = "";
for ( int i=; i<value_extra.size(); ++i )
{
int count = num / value_extra[i];
while ( count--> ) ret = ret + symbol_extra[i];
num = num % value_extra[i];
}
return ret;
}
};