js convert Integer to Roman All In One
js convert Integer to Roman All In One
阿拉伯数字转罗马数字
freecodecamp
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2022-03-09
* @modified
*
* @description
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @time O(n)
* @augments
* @example
* @link https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
function convertToRoman(num) {
// 进位,特殊处理
const map = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let result = '';
for (let key in map) {
// 向下取整
const repeatCounter = Math.floor(num / map[key]);
if (repeatCounter !== 0) {
// 拼接罗马数字字符串
result += key.repeat(repeatCounter);
}
// 获取余数
num %= map[key];
if (num === 0) {
break;
// return result;
}
}
return result;
}
// convertToRoman(1984);
// 'MCMLXXXIV
convertToRoman(36);
/*
(1) should return "I"
(2) should return "II"
(3) should return "III"
(4) should return "IV"
(5) should return "V"
(9) should return "IX"
10 X
(12) should return "XII"
(16) should return "XVI"
(500) should return "D"
(1000) should return "M"
例子:把 1984 转换为 罗马数字。
罗马 1984
把 1984 分成 1000、900、80 和 4,然后逐个转换
1000 = M
900 = CM
80 = LXXX
4 = IV
1000 + 900 + 80 + 4 = 1984,所以 1984 = MCMLXXXIV
*/
罗马数字
https://www.mathsisfun.com/roman-numerals.html
数学乐趣
https://www.shuxuele.com/roman-numerals.html
数学乐
https://www.mathopolis.com/questions/
12. Integer to Roman
Medium
https://leetcode.com/problems/integer-to-roman/
/**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
// 进位,特殊处理
const map = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let result = '';
for (let key in map) {
// 向下取整
const repeatCounter = Math.floor(num / map[key]);
if (repeatCounter !== 0) {
// 拼接罗马数字字符串
result += key.repeat(repeatCounter);
}
// 获取余数
num %= map[key];
if (num === 0) {
break;
// return result;
}
}
return result;
};
refs
https://www.cnblogs.com/xgqfrms/p/13948010.html
©xgqfrms 2012-2025
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15987769.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2021-03-10 万维景盛 西部数码 域名 优惠券
2020-03-10 window.locationbar
2020-03-10 Axios upload excel file All In One
2020-03-10 HTML5 stream video player
2020-03-10 TypeScript Generics All In One
2016-03-10 网页图片优化和性能分析