罗马数与整数的相互转换

相互转换的过程很简单,但是首先第一步就是要搞清楚罗马数字的规律,还是ting有意思的~~~

罗马数字总共有七种字符,对应的数字如下:

                  I               1

                  V              5

                  X             10

                  L               50

                  C              100

                  D               500

                  M              1000

如:I,II,III,IV,V,VI,VII,VIII,IX,X分别对应1,2,3,4,5,6,7,8,9,10。可以发现小于4的,就是I一直叠加,4(IV)是右边的数减去左边的数,大于V小于X就是右边的数加上左边的数,以此类推。。。

下面分别是罗马数转整数和整数转罗马数:

import java.util.HashMap;

import java.util.Scanner;

public class RomanAndInt {

//罗马数转整数

public int RomanToInt(){

Scanner sc =new Scanner(System.in);

String Lnumber=sc.next();

if(Lnumber==null|| Lnumber.length()==0){

return -1;

}

HashMap map=new HashMap();

map.put('I',1);

map.put('V',5);

map.put('X',10);

map.put('L',50);

map.put('C',100);

map.put('D',500);

map.put('M',1000);

int result=map.get(Lnumber.charAt(Lnumber.length()-1));

for(int i=Lnumber.length()-2;i>=0;i--){

if(map.get(Lnumber.charAt(i))>=map.get(Lnumber.charAt(i+1))){

result+=map.get(Lnumber.charAt(i));

}else{

result-=map.get(Lnumber.charAt(i));

}

}

return result;

}

//整数转罗马数

public String IntToRoman(){

Scanner sc=new Scanner(System.in);

int number=sc.nextInt();

StringBuilder sb=new StringBuilder();

String[][] roman={

{"","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"}

};

sb.append(roman[3][number/1000%10]);

sb.append(roman[2][number/100%10]);

sb.append(roman[1][number/10%10]);

sb.append(roman[0][number%10]);

String result=""+sb;

return result;

}

public static void main(String[] args){

RomanAndInt re=new RomanAndInt();

re.RomanToInt();

re.IntToRoman();

}

}

你可能感兴趣的:(罗马数与整数的相互转换)