Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function romanNumeral(number) {
- var input = number;
- var romSinglesChar, romFourChar, romFivesChar, romTensChar, romHundredsChar = '';
- var romanNumeral = [];
- //minimal input validation
- if (input > 1000) {
- console.log("input over limit");
- return;
- }
- //reverse the String
- var reversedInput = input.split("").reverse().join("");
- //console.log(reversedInput);
- //process one digit at a time
- for (index = 1; index <= reversedInput.length; index++) {
- if (reversedInput.length <= 4) {
- var digit = reversedInput[index - 1];
- //calculate the max: 1000
- if (digit == "1" && index == 4) {
- romanNumeral.push("M");
- }
- //calculate 999 and below
- switch (digit) {
- //0
- case "0":
- break;
- //1-3
- case "1":
- case "2":
- case "3":
- romSinglesChar = getRomanSinglesChar(index);
- for (i = 1; i <= parseInt(digit); i++) {
- romanNumeral.push(romSinglesChar);
- }
- break;
- //4
- case "4":
- romFourChar = getRomanFourChar(index);
- romanNumeral.push(romFourChar);
- break;
- //5
- case "5":
- romFivesChar = getRomanFivesChar(index);
- romanNumeral.push(romFivesChar);
- break;
- //6-8
- case "6":
- case "7":
- case "8":
- for (i = 1; i <= parseInt(digit) - 5; i++) {
- romanNumeral.push(getRomanSinglesChar(index));
- }
- romanNumeral.push('V');
- break;
- //9
- case "9":
- romanNumeral.push(getRomanNinesChar(index))
- break;
- }
- }
- }
- return romanNumeral.reverse().toString().split(",").join("");
- }
- //output 1s
- function getRomanSinglesChar(index) {
- switch (index) {
- case 1:
- return "I";
- case 2:
- return "X";
- case 3:
- return "C";
- }
- }
- //output 4s
- function getRomanFourChar(index) {
- switch (index) {
- case 1:
- return "IV";
- case 2:
- return "XL";
- case 3:
- return "CD";
- }
- }
- //output 5s
- function getRomanFivesChar(index) {
- switch (index) {
- case 1:
- return 'V';
- case 2:
- return 'L';
- case 3:
- return 'D';
- }
- }
- //output 9s
- function getRomanNinesChar(index) {
- switch (index) {
- case 1:
- return "IX";
- case 2:
- return "XC";
- case 3:
- return "CM";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement