zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Roman Numeral Converter #325

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

功能

将十进制数字转化为罗马数字。

代码


function convertToRoman(num) {
 var del=[1000,900,500,400,100,90,50,40,10,9,5,4,1];

 var roman=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'];

 var change='';

 for(i=0;i<del.length;i++){
   while(del[i]<=num){
     change+=roman[i];
     num-=del[i];
   }
 }

 return change;
}

convertToRoman(36);

效果

image

参考

JavaScript splice() 方法 JavaScript join() 方法 Roman Numerals

来源: https://www.freecodecamp.org/challenges/roman-numeral-converter

zilongxuan001 commented 6 years ago

此题有些烧脑,于是分解如下 num=36 1.for循环index=8时:

(1)10<=36成立,执行while循环:

romanized=X;

num=36-10=26;

(2)10<=26 成立,执行while循环:

romanized=XX;

num=26-10=16;

(3)10<=16成立,执行while循环;

romanized=XXX;

num=16-10=6;

(4)10>6不成立,跳出while循环。

2.for循环 index=9

9<=6,不成立,跳出while循环;

  1. for循环index=10

5<=6成立,执行while循环: romanzid=V; num=6-5=1;

源代码

var convertToRoman = function(num) {

  var decimalValue = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
  var romanNumeral = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];

  var romanized = '';

  for (var index = 0; index < decimalValue.length; index++) {
    while (decimalValue[index] <= num) {
      romanized += romanNumeral[index];
      num -= decimalValue[index];
    }
  }

  return romanized;
}

// test here
convertToRoman(36);

来源:https://forum.freecodecamp.org/t/freecodecamp-algorithm-challenge-guide-roman-numeral-converter/16044