js convert Integer to Roman All In One
js convert Integer to Roman All In One
阿拉伯数字转罗马数字
freecodecamp
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter
"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
?xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!