码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Roman to Integer

时间:2015-02-25 22:15:34      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

Given a roman numeral, convert it to an integer.

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

保存最典型的,1,5,10,等,然后如果左边的数比右边的小,则减去左边的数,否则相加

package Roman.to.Integer;

import java.util.HashMap;
import java.util.Map;

public class RomantoInteger {
Map<String,Integer> map=new HashMap<String,Integer>();

public void add(int key,String value){
    this.map.put(value, key);
}
public int romanToInt(String s) {
    this.add(1000, "M");
    this.add(500,  "D");
    this.add(100,  "C");
    this.add(50,   "L");
    this.add(10,   "X");
    this.add(5,    "V");
    this.add(1,    "I");
    int i=s.length()-1;
    char a=s.charAt(i);
    String aS=String.valueOf(a);
    int result=this.map.get(aS);
    i--;
    while(i>=0){
    char temp=s.charAt(i);
    String tempS=String.valueOf(temp);
    int curr= this.map.get(tempS);
    char tempNext=s.charAt(i+1);
    String tempNextS=String.valueOf(tempNext);
    int next=this.map.get(tempNextS);
    i--;
    if(next>curr){
        result-=curr;
    }else{
        result+=curr;
    }
    }
    return result;        
    
    }
public static void main(String args[]){
    RomantoInteger service=new RomantoInteger();
    int a=service.romanToInt("IX");
    System.out.println(a);
}
}

 

Leetcode Roman to Integer

标签:

原文地址:http://www.cnblogs.com/criseRabbit/p/4300099.html

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