码迷,mamicode.com
首页 > 编程语言 > 详细

Roman To Integer leetcode java

时间:2015-12-10 11:03:38      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

Given a roman numeral, convert it to an integer.

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

算法:

/**
* 输入一个罗马数字,返回它的整型表示
* @author admin
* 转换规则:从右向左依次转换
* 1 相同数字连写,相加 ;2 小数字在大数字右边,相加;3 小数字在大数字左边,大的减去小的
*/

//将罗马数字转换为整型值
public static int romanToInt(String s){
    HashMap<Character, Integer> roma_weight = new HashMap<Character, Integer>();
    roma_weight.put(‘I‘, 1);
    roma_weight.put(‘V‘, 5);
    roma_weight.put(‘X‘,10);
    roma_weight.put(‘L‘, 50);
    roma_weight.put(‘C‘, 100);
    roma_weight.put(‘D‘,500);
    roma_weight.put(‘M‘,1000);
    char[] roma = s.toCharArray(); //将罗马数字转化为字符数组
    int length = roma.length;
    int preValue = 0; //前一步的value
    int value = roma_weight.get(roma[length - 1]) ;// 当前的value

    //从右向左遍历
    for(int i = length - 2; i >= 0 ; i--){
      //小的数字在大数字右边,直接相加
      if( roma_weight.get(roma[i]) >= roma_weight.get(roma[i + 1])) {
        preValue = value;
        value = value + roma_weight.get(roma[i]);
      }
      else { //小的数字在大数字左边,大的减去小的
        value = preValue + roma_weight.get(roma[i + 1]) - roma_weight.get(roma[i]);
      }
    }
    return value;
}

Roman To Integer leetcode java

标签:

原文地址:http://www.cnblogs.com/mydesky2012/p/5035241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!