1. Description
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
2. Example
input num = 23
output XXIII
3. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C" active ="active"]
#includechar* intToRoman(int num) { char* table[4][10] = { { "", "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" } }; int m = num / 1000, c = num % 1000 / 100, x = num % 100 / 10, i = num % 10; char * result = (char *)malloc(strlen(table[3][m]) + strlen(table[2][c]) + strlen(table[1][x]) + strlen(table[0][i]) + 1); strcpy(result, table[3][m]); strcat(result, table[2][c]); strcat(result, table[1][x]); strcat(result, table[0][i]); return result; } int main() { printf("%s\n", intToRoman(3999)); system("pause"); return 0; }
[/restab]
[restab title="C++"]
#include#include using namespace std; class LeetCode0012 { public: string intToRoman(int num) { string table[4][10] = { { "", "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" } }; return table[3][num / 1000] + table[2][num % 1000 / 100] + table[1][num % 100 / 10] + table[0][num % 10]; } }; int main() { LeetCode0012 leetCode0012 = LeetCode0012(); cout << leetCode0012.intToRoman(3999) << endl; system("pause"); return 0; }
[/restab]
[restab title="C#"]
using System.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Csharp.Digital { [TestClass] public class LeetCode0012 { public string IntToRoman(int num) { string[] m = { "", "M", "MM", "MMM" }; string[] c = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; string[] x = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; string[] i = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; return m[num / 1000] + c[num % 1000 / 100] + x[num % 100 / 10] + i[num % 10]; } [TestMethod] public void Test() { Trace.WriteLine(IntToRoman(23)); } } }
[/restab]
[/restabs]
Comments | NOTHING