https://leetcode.com/problems/integer-to-roman
自己写了一堆啰嗦的规则来选‘最适合’ 的数,结果全是bug。不如直接把数字按位数拆开,然后一一映射来得简洁。
var intToRoman = function(num) { var roman = [ ['','M','MM','MMM'], ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM'], ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC'], ['','I','II','III','IV','V','VI','VII','VIII','IX']] var a = [parseInt(num / 1000) %10, parseInt(num / 100)%10, parseInt(num / 10)%10, num % 10]; console.log(a); return a.map(function(n, i){ return roman[i][n]; }).join(''); }