Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- /*
- * RomanNumeralConverter converts numbers from the Roman Numeral System to
- * regular base-10 numbers and back again.
- * @author hypesystem
- * @version 2012-02-16
- */
- public class RomanNumeralConverter {
- private HashMap<Character,Integer> values;
- public RomanNumeralConverter() {
- values = new HashMap<Character,Integer>();
- values.put('I',1);
- values.put('V',5);
- values.put('X',10);
- values.put('L',50);
- }
- public int fromRoman(String s) {
- int length = s.length();
- int value = 0;
- for(int pos = 0; pos < length; pos++) {
- if(pos < (s.length() - 1) && values.get(s.charAt(pos)) < values.get(s.charAt(pos + 1))) {
- value += (values.get(s.charAt(pos + 1)) - values.get(s.charAt(pos))); pos++;
- }
- else value += values.get(s.charAt(pos));
- }
- return value;
- }
- public static void main(String[] args) {
- RomanNumeralConverter rom = new RomanNumeralConverter();
- rom.test("I");
- rom.test("II");
- rom.test("III");
- rom.test("IV");
- rom.test("V");
- rom.test("VI");
- rom.test("VII");
- rom.test("XVII");
- rom.test("XLIV");
- }
- private void test(String s) {
- StdOut.println(s+" "+fromRoman(s));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment