Guest User

Roman Numeral 2

a guest
Oct 11th, 2011
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. import java.util.Map;
  2. import java.util.SortedMap;
  3. import java.util.TreeMap;
  4.  
  5. /**
  6.  * @author deliveryninja
  7.  *
  8.  * Given a numeral from 1 to 3000 this will return the Roman
  9.  * numberal equivalent.
  10.  *  
  11.  * @param numeral
  12.  * @return
  13.  */
  14. public class Roman {
  15.    
  16.     //Enum is for storing the relationship between the roman representation
  17.     //and an Integer representation.
  18.  
  19.     public enum RomanNumeral{
  20.         M(1000),
  21.         CM(900),
  22.         D(500),
  23.         CD(400),
  24.         C(100),
  25.         XC(90),
  26.         L(50),
  27.         XL(40),
  28.         X(10),
  29.         IX(9),
  30.         V(5),
  31.         IV(4),
  32.         I(1);
  33.        
  34.         private int value;
  35.        
  36.         RomanNumeral(int value){
  37.             this.value = value;
  38.         }
  39.  
  40.         public int getIntegerValue() {
  41.             return value;
  42.         }      
  43.     }
  44.    
  45.     /**
  46.     *   Method for converting the give numeral to a roman String representation.
  47.     *
  48.     **/
  49.     public String romanize(int numeral) {
  50.  
  51.         //Initialise a StringBuilder to store the result
  52.         StringBuilder result = new StringBuilder();
  53.  
  54.         //Loop through the roman numerals in order, starting with the largest.
  55.         for(RomanNumeral romanNumeral : RomanNumeral.values()){
  56.  
  57.             //Check given numeral is larger than the roman numeral
  58.             while(numeral >= romanNumeral.getIntegerValue()){
  59.                
  60.                 //Update the result        
  61.                 result.append(romanNumeral);  
  62.  
  63.                 //Reduce the given value
  64.                 numeral -= romanNumeral.getIntegerValue();
  65.             }
  66.         }
  67.         //Finally return the result
  68.         return result.toString();
  69.     }
  70.  
  71. }
  72.  
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment