Even though this program seems simple, the algorithm is bit complex. When we convert a Roman number to Hindu-Arabic number manually, we do it in the following manner.
MCMXLIV = 1000 + (1000 − 100) + (50 − 10) + (5 − 1) = 1944
Value of each number is added together. When smaller values precede larger values, the smaller values are subtracted from the larger values, and the result is added to the total.This algorithm use above technique to the conversion. "for" loop gets each character of the roman number string from the beginning and gets its integer value from the "getInt()" method. At each iteration character is compared with the next character value. If the next character is the same, the value is added to mediator to add in the next iteration. If it is large, the value is added to mediator to subtract in the next iteration.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Converting Roman number to Arabic number | |
public static int convertRomToInt(String romanNum) { | |
int result = 0; | |
int mediator = 0; | |
int length = romanNum.length(); //get number string length | |
for (int i = 0; i < length - 1; i++) { //this loop will add each Roman character value | |
if (getInt(romanNum.charAt(i)) > getInt(romanNum.charAt(i + 1))) { | |
result = result + getInt(romanNum.charAt(i)) + mediator; | |
mediator = 0; | |
} else if (getInt(romanNum.charAt(i)) == getInt(romanNum.charAt(i + 1))) { | |
mediator = mediator + getInt(romanNum.charAt(i)); | |
} else if (getInt(romanNum.charAt(i)) < getInt(romanNum.charAt(i + 1))) { | |
mediator = -mediator - getInt(romanNum.charAt(i)); | |
} | |
} | |
result = result + mediator + getInt(romanNum.charAt(length - 1)); | |
return result; | |
} | |
//Get integer value for corresponding Roman character | |
public static int getInt(char romanChar) { | |
if (romanChar == 'I') | |
return 1; | |
else if (romanChar == 'V') { | |
return 5; | |
} else if (romanChar == 'X') { | |
return 10; | |
} else if (romanChar == 'L') { | |
return 50; | |
} else if (romanChar == 'C') { | |
return 100; | |
} else if (romanChar == 'D') { | |
return 500; | |
} else if (romanChar == 'M') { | |
return 1000; | |
} | |
return (Integer) null; | |
} |
will it work for invalid inputs?
ReplyDeleteno work?
ReplyDeleteWhat about reducing the string for each time it loops?
ReplyDeleteHi Fille,
ReplyDeleteI didn't get your question. Can you please rephrase it?
thanks ur code helped me a lot
ReplyDeleteThanks for sharing
ReplyDelete