问题描述
我正在研究FreeCodeCamp课程中的中间算法.其中之一涉及将整数转换为罗马数字.我的解决方案(如下所示)是可行的,但是如果您愿意的话,它是非常幼稚"的方法.该任务提示应使用array.splice(),array.indexOf()和array.join().我的实现只使用array.join().
I'm working through the intermediate algorithms in the FreeCodeCamp curriculum. One of them involves converting integers to roman numerals. My solution (presented below) works, however it is very much the "naive" approach, if you will. The task hints that array.splice(), array.indexOf(), and array.join() ought to be used. My implementation only uses array.join().
针对精度的经过编辑的问题:有人会提供一种使用上述方法的 all 的实现吗?
Edited question for precision: Will someone provide an implementation that makes use of all of the aforementioned methods?
谢谢.
我的实现:
function convertToRoman(num) {
var I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000;
var numerals = [];
var i;
if(num >= 1000){
var numMs = Math.floor(num / 1000);
for (i = 0; i < numMs; i++){
numerals.push('M');
}
num = num % 1000;
}
if(num >= 900){
numerals.push('CM');
num = num - 900;
}
if(num < 900){
if(num >= 500){
numerals.push('D');
num = num - 500;
}
if(num >= 400){
numerals.push('CD');
num = num - 400;
}
var numCs = Math.floor(num / 100);
for(i = 0; i < numCs; i++){
numerals.push('C');
}
num = num % 100;
}
if(num >= 90){
numerals.push('XC');
num = num - 90;
}
if(num < 90){
if(num >= 50){
numerals.push('L');
num = num - 50;
}
if(num >= 40){
numerals.push('XL');
num = num - 40;
}
var numXs = Math.floor(num / 10);
for(i = 0; i < numXs; i++){
numerals.push('X');
}
num = num % 10;
}
if(num == 9){
numerals.push('IX');
num = num - 9;
}
if(num < 9){
if(num >= 5){
numerals.push('V');
num = num - 5;
}
if(num >=4){
numerals.push('IV');
num = num - 4;
}
var numIs = Math.floor(num / 1);
for(i = 0; i < numIs; i++){
numerals.push('I');
}
}
var converted = numerals.join('');
return converted;
}
更新:在此处,但是它不使用我感兴趣的方法.
UPDATE: Another answer found here, but it does not use the methods I'm interested in using.
推荐答案
您可以执行以下操作;
You may do as follows;
function toRoman(n){
var numerals = ["I","V","X","L","C","D","M"];
return n.toString()
.split("")
.reverse()
.reduce((p,c,i) => (c === "0" ? ""
: c < "4" ? numerals[2*i].repeat(c)
: c === "4" ? numerals[2*i] + numerals[2*i+1]
: c < "9" ? numerals[2*i+1] + numerals[2*i].repeat(c-5)
: numerals[2*i] + numerals[2*i+2]) + p,"");
}
console.log(toRoman(1453));
这篇关于将整数转换为罗马数字-必须有更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!