Intger To Roman
這題意思是將一個輸入的整型阿拉伯數字轉化為羅馬數字。
思路是將1-10對應的羅馬數字放在字符串數組里,然后發現數據變化規律即可,eg:389 = 300 + 89 +9 分別對應的羅馬數字。
public static void main(String[] args) {
String[] strs = {"I","II","III","IV","V","VI","VII","VIII","IX","X"};
Scanner input = new Scanner(System.in);
System.out.print("請輸入一個1-3999整數:");
int n = input.nextInt();
if(n < 1 || n >3999){
System.out.print("輸入超出范圍!");
}else{
String result = toRomanNumeral(strs,n);
System.out.println(result);
}
}
public static String toRomanNumeral(String[] strs, int n) {
StringBuffer sb = new StringBuffer();
if(n > 0 && n <= 10){
sb.append(strs[n-1]);
}else if(n>10 && n <=100){
sb.append(zhuanHua(n/10,strs)).append(strs[n%10-1]);
}else if(n>100 && n <= 1000){
sb.append(zhuanHua2(n/100,strs)).append(zhuanHua(n%100/10,strs)).append(strs[n%100%10-1]);
}else if(n>1000 && n <= 3999){
for(int i = 0; i < n/1000; ++i){
sb.append("M");
}
n%=1000;
sb.append(zhuanHua2(n/100,strs)).append(zhuanHua(n%100/10,strs)).append(strs[n%100%10-1]);
}else{
sb.append("輸入超出范圍!");
}
return sb.toString();
}
public static String zhuanHua2(int i, String[] strs) {
StringBuffer sb = new StringBuffer();
for(int j = 0; j < strs[i-1].length(); ++j){
char temp = strs[i-1].charAt(j);
if(temp == 'X'){
temp = 'M';
}else if(temp == 'I'){
temp = 'C';
}else if(temp == 'V'){
temp = 'D';
}
sb.append(temp);
}
return sb.toString();
}
public static String zhuanHua(int i, String[] strs) {
StringBuffer sb = new StringBuffer();
for(int j = 0; j < strs[i-1].length(); ++j){
char temp = strs[i-1].charAt(j);
if(temp == 'X'){
temp = 'C';
}else if(temp == 'I'){
temp = 'X';
}else if(temp == 'V'){
temp = 'L';
}
sb.append(temp);
}
return sb.toString();
}
轉載于:https://www.cnblogs.com/huaiyinxiaojiang/p/6497341.html
總結
以上是生活随笔為你收集整理的Intger To Roman的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库及线程死锁(转)
- 下一篇: SQL查询库、表,列等的一些操作