12.整数转罗马数字
链接:12.整数转罗马数字
难度:Medium
标签:哈希表、数学、字符串
简介:给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
题解 1 - typescript
- 编辑时间:2020-06-02
- 执行用时:144ms
- 内存消耗:41.3MB
- 编程语言:typescript
- 解法介绍:递归判断每一位。
function intToRoman(num: number): string {
const len = (num + '').length;
let s = '';
switch (len) {
case 4: {
const n = ~~(num / 1000);
for (let i = 0; i < n; i++) s += 'M';
s += intToRoman(num % 1000);
break;
}
case 3: {
const n = ~~(num / 100);
switch (n) {
case 9: {
s += 'CM';
break;
}
case 8: {
s += 'DCCC';
break;
}
case 7: {
s += 'DCC';
break;
}
case 6: {
s += 'DC';
break;
}
case 5: {
s += 'D';
break;
}
case 4: {
s += 'CD';
break;
}
case 3: {
s += 'CCC';
break;
}
case 2: {
s += 'CC';
break;
}
case 1: {
s += 'C';
break;
}
}
s += intToRoman(num % 100);
break;
}
case 2: {
const n = ~~(num / 10);
switch (n) {
case 9: {
s += 'XC';
break;
}
case 8: {
s += 'LXXX';
break;
}
case 7: {
s += 'LXX';
break;
}
case 6: {
s += 'LX';
break;
}
case 5: {
s += 'L';
break;
}
case 4: {
s += 'XL';
break;
}
case 3: {
s += 'XXX';
break;
}
case 2: {
s += 'XX';
break;
}
case 1: {
s += 'X';
break;
}
}
s += intToRoman(num % 10);
break;
}
case 1: {
switch (num) {
case 9: {
s += 'IX';
break;
}
case 8: {
s += 'VIII';
break;
}
case 7: {
s += 'VII';
break;
}
case 6: {
s += 'VI';
break;
}
case 5: {
s += 'V';
break;
}
case 4: {
s += 'IV';
break;
}
case 3: {
s += 'III';
break;
}
case 2: {
s += 'II';
break;
}
case 1: {
s += 'I';
break;
}
}
break;
}
}
return s;
}
题解 2 - typescript
- 编辑时间:2021-05-14
- 执行用时:212ms
- 内存消耗:44.3MB
- 编程语言:typescript
- 解法介绍:分节处理。
const config: Map<number, Map<number, string>> = new Map([
[
100,
new Map([
[1, 'C'],
[5, 'D'],
[10, 'M'],
]),
],
[
10,
new Map([
[1, 'X'],
[5, 'L'],
[10, 'C'],
]),
],
[
1,
new Map([
[1, 'I'],
[5, 'V'],
[10, 'X'],
]),
],
]);
function intToRoman(num: number): string {
let ans = '';
if (num >= 1000) {
ans += 'M'.repeat(~~(num / 1000));
num = num % 1000;
}
for (const [val, map] of config) {
if (num < val) continue;
const c1 = map.get(1)!;
const c5 = map.get(5)!;
const c10 = map.get(10)!;
const c = ~~(num / val);
num = num % val;
if (c === 9) ans += c1 + c10;
else if (c >= 5) ans += c5 + c1.repeat(c - 5);
else if (c === 4) ans += c1 + c5;
else ans += c1.repeat(c);
}
return ans;
}
题解 3 - typescript
- 编辑时间:2021-10-16
- 执行用时:148ms
- 内存消耗:44.2MB
- 编程语言:typescript
- 解法介绍:模拟。
function intToRoman(num: number): string {
let ans = '';
const list: { val: number; template: [string, string, string] }[] = [
{
val: 1000,
template: ['M', 'M', 'M'],
},
{
val: 100,
template: ['M', 'D', 'C'],
},
{
val: 10,
template: ['C', 'L', 'X'],
},
{
val: 1,
template: ['X', 'V', 'I'],
},
];
for (const { val, template } of list) {
if (num >= val) {
ans += createStr(Math.floor(num / val), ...template);
num %= val;
}
}
return ans;
function createStr(num: number, hight: string, mid: string, low: string) {
if (num <= 3) return low.repeat(num);
else if (num <= 5) return low.repeat(5 - num) + mid;
else if (num <= 8) return mid + low.repeat(num - 5);
else return low + hight;
}
}