[leetcode] 12. Integer to Roman

来源:互联网 发布:任意门软件下载 编辑:程序博客网 时间:2024/06/04 00:21

题目:

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字:

罗马数字记数的方法:
1.相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
2.小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
3.小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
4.在一个数的上面画一条横线,表示这个数增值 1,000 倍,如 =5000。


个位数举例
Ⅰ,1 】Ⅱ,2】 Ⅲ,3】 Ⅳ,4 】Ⅴ,5 】Ⅵ,6】Ⅶ,7】 Ⅷ,8 】Ⅸ,9 】
十位数举例
Ⅹ,10】 Ⅺ,11 】Ⅻ,12】 XIII,13】 XIV,14】 XV,15 】XVI,16 】XVII,17 】XVIII,18】 XIX,19】 XX,20】 XXI,21 】XXII,22 】XXIX,29】 XXX,30】 XXXIV,34】 XXXV,35 】XXXIX,39】 XL,40】 L,50 】LI,51】 LV,55】 LX,60】 LXV,65】 LXXX,80】 XC,90 】XCIII,93】 XCV,95 】XCVIII,98】 XCIX,99 】
百位数举例
C,100】 CC,200 】CCC,300 】CD,400】 D,500 】DC,600 】DCC,700】 DCCC,800 】CM,900】 CMXCIX,999】
千位数举例
M,1000】 MC,1100 】MCD,1400 】MD,1500 】MDC,1600 】MDCLXVI,1666】 MDCCCLXXXVIII,1888 】MDCCCXCIX,1899 】MCM,1900 】MCMLXXVI,1976】 MCMLXXXIV,1984】 MCMXC,1990 】MM,2000 】MMMCMXCIX,3999】

    public String intToRoman(int num){    StringBuilder sb=new StringBuilder();    int[] nums=new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};      String[] romans=new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};    while(num>0){    for(int i=0;i<nums.length;i++){    if(num>=nums[i]){    sb.append(romans[i]);    num-=nums[i];    break;    }       }    }    return sb.toString();    }

类似的13.整数转罗马数字

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

    public int romanToInt(String s) {        Map<Character,Integer> map=new HashMap<Character,Integer>();        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 number=0;        for(int i=0;i<s.length();i++){            if(i>0&&map.get(s.charAt(i))<=map.get(s.charAt(i-1))||i==0)                number+=map.get(s.charAt(i));            else                number+=map.get(s.charAt(i))-2*map.get(s.charAt(i-1));        }        return number;        }