| 1 | public class RomanToInteger{ |
| 2 | public static int GetNum(int num) {//gets the number assoicate with a roman character |
| 3 | if (num == 'I' || num == 'i') { |
| 4 | return 1; |
| 5 | } |
| 6 | if (num == 'V' || num == 'v') { |
| 7 | return 5; |
| 8 | } |
| 9 | if (num == 'X' || num == 'x') { |
| 10 | return 10; |
| 11 | } |
| 12 | if (num == 'L' || num == 'l') { |
| 13 | return 50; |
| 14 | } |
| 15 | if (num == 'C' || num == 'c') { |
| 16 | return 100; |
| 17 | } |
| 18 | if (num == 'D' || num == 'd') { |
| 19 | return 500; |
| 20 | } |
| 21 | if (num == 'M' || num == 'm') { |
| 22 | return 1000; |
| 23 | } |
| 24 | |
| 25 | return -1; |
| 26 | } |
| 27 | |
| 28 | public static int romanToNumber(String roman){//Converts a roman numerial into a number |
| 29 | int results = 0; |
| 30 | for (int i = 0; i < roman.length(); i++) {//iterate through all the characters |
| 31 | int cur = GetNum(roman.charAt(i));//Gets the integer of the roman number |
| 32 | if (cur == -1) {//checks if the cur num is -1, if it is -1, it means that it is an invalid character |
| 33 | return -1; |
| 34 | } |
| 35 | if (i + 1 < roman.length()) {//checks if the next index is out of bounds |
| 36 | int next = GetNum(roman.charAt(i + 1));//gets the next character character |
| 37 | if (next == -1) {//checks if the cur num is -1, if it is -1, it means that it is an invalid character |
| 38 | return -1; |
| 39 | } |
| 40 | if (cur >= next) {//compares the current number to the next number |
| 41 | results += cur;//if it is bigger, simply add the current number |
| 42 | } |
| 43 | else {//if the current number is smaller than the next number |
| 44 | results += (next - cur);//subtract the next number by the current number |
| 45 | i++;//increment the index, since the next number has already been used |
| 46 | } |
| 47 | } |
| 48 | else {//only here to add the last number to the results |
| 49 | results += cur;//adds the last character to the results |
| 50 | } |
| 51 | } |
| 52 | return results;//returns the result |
| 53 | } |
| 54 | } |
nothing calls this directly
no outgoing calls
no test coverage detected