Skip to content

Instantly share code, notes, and snippets.

@ApsarasX
Created August 28, 2017 13:33
Show Gist options
  • Save ApsarasX/804c6e14e2c2636cf13363a7d188e1e1 to your computer and use it in GitHub Desktop.
Save ApsarasX/804c6e14e2c2636cf13363a7d188e1e1 to your computer and use it in GitHub Desktop.
Int to Roman(整数转为罗马数字)(1-3999999)
function convert(num) {
// suppose num>0&&num<4000000
if(!Number.isInteger(num)) {
throw 'Sorry, there are only integers in Rome numerals.';
} else if(num<0) {
throw 'Sorry, there is no negative in Roman numerals.';
} else if(num===0) {
throw 'Sorry, there is no zero in Roman numerals.';
} else if(num>=4000000) {
throw 'Sorrt, 4000000 and more are too high.';
}
let numStr = num.toString(),
len = numStr.length,
numObj = [];
for (let i = 0; i < len; i++) {
numObj.push({
weight: Math.pow(10, len - i - 1),
value: parseInt(numStr[i])
});
}
const romanObj = {
'1': 'I',
'5': 'V',
'10': 'X',
'50': 'L',
'100': 'C',
'500': 'D',
'1000': 'M',
'5000': 'V`',
'10000': 'X`',
'50000': 'L`',
'100000': 'C`',
'500000': 'D`',
'1000000': 'M`',
};
let retStr = numObj.map(function (item) {
switch (item.value) {
case 0:
case 1:
case 2:
case 3:
return romanObj[item.weight.toString()].repeat(item.value);
case 4:
case 5:
return romanObj[item.weight.toString()].repeat(5-item.value)+romanObj[5*item.weight.toString()];
case 6:
case 7:
case 8:
return romanObj[5*item.weight.toString()]+romanObj[item.weight.toString()].repeat(item.value-5);
case 9:
return romanObj[item.weight.toString()]+romanObj[10*item.weight.toString()];
}
}).join('');
return retStr;
}
let x = convert(123);
console.log(x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment