Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Roman Numerals

807589Oct 27 2008 — edited Oct 28 2008
What is the simplest way to turn a String of Roman Numerals into their true value as an integer?

I am using this for computer science competitions so it is important to know the shortest/fastest way to solve this problem. Since this is a pretty common problem I figured finding a faster way to do it would be valuable.

This is my current code. and yes I know i need to replace that map with an arraylist.
import java.io.*;
import java.util.*;
import java.text.*;
import static java.lang.System.*;
import static java.lang.Integer.*;
import static java.lang.Double.*;
import static java.lang.Character.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;


public class adv51
{
	public void run()throws Exception
	{
		Scanner file=new Scanner(new File("adv51.dat"));
		int loops=file.nextInt();
		file.nextLine();
		Map<String,Integer> values=new HashMap<String,Integer>();
		values.put("IV",4);
		values.put("IX",9);
		values.put("XL",40);
		values.put("XC",90);
		values.put("CD",400);
		values.put("CM",900);
		values.put("M",1000);
		values.put("D",500);
		values.put("C",100);
		values.put("L",50);
		values.put("X",10);
		values.put("V",5);
		values.put("I",1);
		ArrayList<String> keys=new ArrayList<String>();
		keys.add("IV");
		keys.add("IX");
		keys.add("XL");
		keys.add("XC");
		keys.add("CD");
		keys.add("CM");
		keys.add("M");
		keys.add("D");
		keys.add("C");
		keys.add("L");
		keys.add("X");
		keys.add("V");
		keys.add("I");
		for(int loop=0;loop<loops;loop++)
		{
			String numeral=file.nextLine();
			int value=0;
			Iterator i=keys.iterator();
			while(i.hasNext())
			{
				String s=(String)i.next();
				while(numeral.indexOf(s)>=0)
				{
					numeral=numeral.replaceFirst(s,"");
					value+=values.get(s);
				}
			}
			System.out.println(value);
		}
	}
	
	public static void main(String[] args)throws Exception
	{
		adv51 a=new adv51();
		a.run();
	}	
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 25 2008
Added on Oct 27 2008
12 comments
329 views