罗马数字---int转换

来源:互联网 发布:5元已备案域名批发购买 编辑:程序博客网 时间:2024/05/06 02:46

罗马数字:

I: 1;    V:5;    X:10  L:50    C:100   D:500   M:1000

4:IV     9:IX 

40: XL   90:XC

400:CD  900:CM

1.int 转为Roman

public class Solution {    private int[] val = {            1000, 900, 500, 400,            100, 90, 50, 40,            10, 9, 5, 4,            1    };    private String[] syb = new String[] {            "M", "CM", "D", "CD",            "C", "XC", "L", "XL",            "X", "IX", "V", "IV",            "I"    };    public String intToRoman(int num) {        StringBuilder roman = new StringBuilder();        int i = 0, k;        while (num > 0) {            k = num / val[i];            while (k-- > 0) {                roman.append(syb[i]);                num -= val[i];            }            i++;        }        return roman.toString();    }}

2.Roman-------int


public class Solution {  public static int romanToInt(String s) {        char [] c={'I','V','X','L','C','D','M'};        int [] a={1,5,10,50,100,500,1000};        Map<Character,Integer> map=new HashMap<Character,Integer>();        for(int i=0;i<c.length;i++){            map.put(c[i],a[i]);        }                       //int result=map.get(s.charAt(0));        int length = s.length();    int result = map.get(s.charAt(length - 1));    for (int i = length - 2; i >= 0; i--) {        if (map.get(s.charAt(i + 1)) <= map.get(s.charAt(i))) {            result += map.get(s.charAt(i));        } else {            result -= map.get(s.charAt(i));        }    }    return result;    }     }


0 0
原创粉丝点击