NC361. 整数转罗马数字
描述
示例1
输入:
5
输出:
"V"
示例2
输入:
6
输出:
"VI"
C++ 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-07-31
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串 */ string ArabicToRoman(int n) { // write code here string temp = ""; pair<int, string> pairVec[] = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} }; for(auto iter:pairVec) { while(iter.first<=n) { n = n - iter.first; temp+=iter.second; } if(n==0) { break; } } return temp; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-07-26
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串 */ string ArabicToRoman(int n) { // write code here static const char* ws[] = {"I", "IV", "V", "IX","X", "XL", "L","XC", "C", "CD", "D", "CM", "M"}; static const int ns[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}; string res; int idx = 12; while(n) { if(n >= ns[idx]) { //cout << n << " " << ns[idx] <<" " << ws[idx] << endl; res.append(ws[idx]); n -= ns[idx]; } else { idx --; } } return res; } };
C 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-07-07
const int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const char* symbols[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; char* ArabicToRoman(int n) { char* roman = malloc(sizeof(char) * 16); roman[0] = '\0'; for (int i = 0; i < 13; i++) { while (n >= values[i]) { n -= values[i]; strcpy(roman + strlen(roman), symbols[i]); } if (n == 0) {break;} } return roman; }
C 解法, 执行用时: 3ms, 内存消耗: 412KB, 提交时间: 2022-03-20
const int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const char* symbols[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; char* ArabicToRoman(int num) { // write code here char* roman = malloc(sizeof(char) * 16); roman[0] = '\0'; for (int i = 0; i < 13; i++) { while (num >= values[i]) { num -= values[i]; strcpy(roman + strlen(roman), symbols[i]); } if (num == 0) { break; } } return roman; }
C++ 解法, 执行用时: 3ms, 内存消耗: 464KB, 提交时间: 2022-08-02
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串 */ string ArabicToRoman(int n) { // write code here int num=n; vector<vector<string> > c={ {"","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 roman; roman.append(c[3][num / 1000 % 10]); roman.append(c[2][num / 100 % 10]); roman.append(c[1][num / 10 % 10]); roman.append(c[0][num % 10]); return roman; } };