Saturday, August 8, 2015

Roman to Decimal

Converting Roman String to Decimal

Input: VI
Output : 6



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class RomanToDecimal{
   public static void romanToDecimal(String romanNumber){
       int decimal = 0;
       int lastNumber = 0;
       String romanNumeral = romanNumber.toUpperCase();
       for (int x = romanNumeral.length() - 1; x >= 0 ; x--){
           char convertToDecimal = romanNumeral.charAt(x);
           switch (convertToDecimal){
               case 'M':
                   decimal = processDecimal(1000, lastNumber, decimal);
                   lastNumber = 1000;
                   break;
               case 'D':
                   decimal = processDecimal(500, lastNumber, decimal);
                   lastNumber = 500;
                   break;
               case 'C':
                   decimal = processDecimal(100, lastNumber, decimal);
                   lastNumber = 100;
                   break;
               case 'L':
                   decimal = processDecimal(50, lastNumber, decimal);
                   lastNumber = 50;
                   break;
               case 'X':
                   decimal = processDecimal(10, lastNumber, decimal);
                   lastNumber = 10;
                   break;
               case 'V':
                   decimal = processDecimal(5, lastNumber, decimal);
                   lastNumber = 5;
                   break;
               case 'I':
                   decimal = processDecimal(1, lastNumber, decimal);
                   lastNumber = 1;
                   break;
           }
       }
       System.out.println("Decimal number : "+decimal);
   }
   
   public static int processDecimal(int decimal, int lastNumber, int lastDecimal){
       if (lastNumber > decimal)
           return lastDecimal - decimal;
       else
           return lastDecimal + decimal;
   }
   
   public static void main(java.lang.String args[]){
      String roman = "VI";
      romanToDecimal(roman);
   }
}

No comments:

Post a Comment