标签:
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); } }
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4300099.html