题目:
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<1 ) return NULL; const int size = 7; std::string symbol_ori[size] = {"M","D","C","L","X","V","I"}; int value_ori[size] = {1000,500,100,50,10,5,1}; // gain extra symbol and value pair std::vector<std::string> symbol_extra; std::vector<int> value_extra; for ( int i = 0; i < size-1; ++i ){ symbol_extra.push_back(symbol_ori[i]); value_extra.push_back(value_ori[i]); if ( !(i & 1) ){ symbol_extra.push_back(symbol_ori[i+2]+symbol_ori[i]); value_extra.push_back(value_ori[i]-value_ori[i+2]); } else{ symbol_extra.push_back(symbol_ori[i+1]+symbol_ori[i]); value_extra.push_back(value_ori[i]-value_ori[i+1]); } } symbol_extra.push_back(symbol_ori[size-1]); value_extra.push_back(value_ori[size-1]); std::string result; for ( size_t i = 0; 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<1 ) return NULL; const int size = 7; string symbol_ori[size] = {"M","D","C","L","X","V","I"}; int value_ori[size] = {1000,500,100,50,10,5,1}; vector<string> symbol_extra; vector<int> value_extra; for ( int i=0; i<size-1; ++i ){ symbol_extra.push_back(symbol_ori[i]); value_extra.push_back(value_ori[i]); if ( !(1 & i) ) { symbol_extra.push_back(symbol_ori[i+2]+symbol_ori[i]); value_extra.push_back(value_ori[i]-value_ori[i+2]); } else { symbol_extra.push_back(symbol_ori[i+1]+symbol_ori[i]); value_extra.push_back(value_ori[i]-value_ori[i+1]); } } symbol_extra.push_back(symbol_ori[size-1]); value_extra.push_back(value_ori[size-1]); string ret = ""; for ( int i=0; i<value_extra.size(); ++i ) { int count = num / value_extra[i]; while ( count-->0 ) ret = ret + symbol_extra[i]; num = num % value_extra[i]; } return ret; } };