Javascript 将阿拉伯数字转换成罗马数字
羅馬數字真的很神奇
Examples: They wrote V instead of 5
And wrote IX instead of 9
首先,了解羅馬數字
| 1 | I |
| 10 | X |
| 50 | L |
| 100 | C |
| 500 | D |
| 1000 | M |
其次,羅馬數字的表示方法中的規則
1、
When a symbol appears after a larger symbol it is added
當一個符號左邊大于右邊時,兩個符號相加表示數值大小
Example: VI = V + I = 5 + 1 = 6
2、
But if the symbol appears before a larger symbol it is subtracted
但是,當符號左邊小于右邊時,右邊符號減去左邊表示數值大小(10以內)
Example: IX = X - I = 10 - 1 = 9
3、
Don’t use the same symbol more than three times in a row (but IIII is sometimes used for 4, particularly on clocks)
不要將一個符號使用超過三次,在鐘的表示里面例外
解題思路
第一步:將阿拉伯數字拆分開來,可以通過toString()方法(法二),也可以通過下面的先取余后除的方法,按照數字從高位到低位的方法逐個將各位的數字獲取出*(法一)*
第二步:構建一個二維數組,將各個位數可能出現的數值大小表示出來
第三步:將大象放進去
第四步:關上門
Javascript代碼(法一)
function convert(num){if(isNaN(num)) return num;var a=[["","I","II","III","IV","V","VI","VII","VIII","IX"],["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],["","M","MM","MMM"]];var roman = "";var t=0;for(var m = 0, i = 10000; m < 4; m++,i /= 10){t=Math.floor((num%i)/(i/10));roman += a[3-m][t];}return roman;}convert(36);Javascript代碼(法二)
function convert(num){if(isNaN(num)) return num;var a=[["","I","II","III","IV","V","VI","VII","VIII","IX"],["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],["","M","MM","MMM"]];var s = num.toString();var arr = [];var b = 0;for(var m = 0; m < s.length; m++){b=a[((s.length)-(m+1))][s[m]];//竟然忘了數組怎么用,卡了半天,真的難受233alert(b);arr.push(b);}b = arr.join("");return b;}convert(36);結語
真的還是要多練習,這么一個不是很復雜的題目看了將近三個小時,很難受香菇哈哈哈
總結
以上是生活随笔為你收集整理的Javascript 将阿拉伯数字转换成罗马数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: firefox改html内容,可以fir
- 下一篇: java 罗马数字_JAVA,罗马数字与