12. Integer to Roman&&13. Roman to Integer

来源:互联网 发布:淘宝客户投诉电话 编辑:程序博客网 时间:2024/05/22 13:35
  • Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.

  • 找出数字和罗马数字的转化关系就可以了

    规律如下
    罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:
    1、相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
    2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
    3、小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
    4、正常使用时、连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外);

public class Solution {    public String intToRoman(int num) {        String M[] = {"", "M", "MM", "MMM"};        String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};        String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};        String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};        return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];    }}

Given a roman numeral, convert it to an integer.

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