LeetCode: Integer to Roman and Roman to Integer

Given a roman numeral, convert it to an integer.

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

其实这两道题只是把输入输出反过来而已。不过在写代码之前,还是了解了Roman数字的表示方法。

基本字符                           I       V       X       L       C       D       M

相应的阿拉伯数字表示为        1       5       10     50     100    500    1000

有几条须注意掌握:

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

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

  3. V 和X 左边的小数字只能用Ⅰ。

  4. L 和C 左边的小数字只能用X。

  5. D 和M 左边的小数字只能用C。

Integer to Roman:关键在于900-1000,400-500,90-100,40-50,9,4.由于基本数字不超过3个导致了这些数字的特殊性,要把某些小的数字放在大数字左边,这样的结果是相减的结果。

Roman to Integer:HashMap把roman作为关键字,把其代表值作为value。关键在于如果判断有一些减法情况。在这样其实选择了最简单的,i+1的value大于i的value的话,得到的值为get(s(i+1))-get(s(i));并把i向后移动2个。


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


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

转载于:https://www.cnblogs.com/jessiading/p/3745674.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值