LeetCode----- 13.Roman to Integer

来源:互联网 发布:淘宝在哪修改收货地址 编辑:程序博客网 时间:2024/06/15 00:50

Given a roman numeral, convert it to an integer.

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

罗马记数方法:

基本字符

I

V

X

L

C

D

M

相应的阿拉伯数字表示为

1

5

10

50

100

500

1000

  1. 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;

  2. 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;

  3. 小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;

  4. 正常使用时、连写的数字重复不得超过三次;

  5. 在一个数的上面画一条横线、表示这个数扩大 1000 倍。

组数规则:

有两条须注意掌握:

  1. 基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;

  2. 不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;

本题解题思路:因为输入的罗马数字是正确的,不需要我们判断,则只要判断当前的罗马数字与下一个罗马数字大小的比较,如果大于后一个数,则加上当前的数;如果小于后一个数,就减去当前的数。最重要的一点,记得加上字符串的最后一位,因为它没有比较的对象了。

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



第二种写法:

public static int romanToInt_2(String s) {    Map<Character,Integer> map = new HashMap<Character, Integer>(){    {    put('I',1);    put('V',5);    put('X',10);    put('L',50);    put('C',100);    put('D',500);        put('M',1000);    }    };    int result = 0;    int pre = 0;//前一位数    int cur =0;//当前数    result = map.get(s.charAt(0));    for (int i = 1; i < s.length(); i++) {    pre = map.get(s.charAt(i-1));    cur = map.get(s.charAt(i));    if(cur <= pre) {    result += cur;    }else {result = result - (2*pre) + cur;}}       return result;    }