12. Integer to Roman(整數轉羅馬數字)
阿新 • • 發佈:2019-02-07
給定一個整數,將其轉為羅馬數字。
輸入保證在 1 到 3999 之間。
解題思路:每一個不同權值的數字都有相應的羅馬數字與之對應,建立一個數組,然後用除運算和模運算得到不同權值的數字並對應輸出即可。
class Solution {
public static String intToRoman(int num) {
String[] romanPieces={"","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","MMMM"};
return romanPieces[num/1000+30]+romanPieces[(num/100)%10+20]
+romanPieces[(num/10)%10+10]+romanPieces[num%10];
}
}