Wednesday, May 9, 2012

Decimal to Roman Conversion using Java



import java.io.*;
public class RomanConversion
{  
    // Parallel arrays used in the conversion process.
    private static final String[] RCODE = {"M", "CM", "D", "CD", "C", "XC", "L","XL","X","IX", "V","IV","I"};
    private static final int[]    BVAL  = {1000, 900, 500, 400,  100,  90,  50, 40,  10,   9,   5,  4,   1};
    public static String binaryToRoman(int binary)
    {
       if (binary <= 0 || binary >= 4000)
       throw new NumberFormatException("Value Outside Roman Numeral Range");
       String roman="";// Roman notation will be accumualated here.      
       // Loop from biggest value to smallest, successively subtracting,
       // from the binary value while adding to the roman representation.
       for (int i=0;i<RCODE.length;i++)
       {
           while (binary>=BVAL[i])
           {
               binary-=BVAL[i];
                roman+=RCODE[i];
           }
       }
       return roman;
   }
   public static void main(String args[])throws IOException
   {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter The Number:");
     int no=Integer.parseInt(br.readLine());
     System.out.print("Roman: "+binaryToRoman(no));
   }
}
//--------------------------------------------------------------------------
/**
 Output:-

 Enter The Number:1995
 Roman: MCMXCV

 Enter The Number:880
 Roman: DCCCLXXX

 Enter The Number:3818
 Roman: MMMDCCCXVIII
 */

Reactions:

0 comments:

Post a Comment