I request you to please read this before marking as Duplicate.
I have referred to below:
After understanding, I have designed following algorithm to convert roman to decimal.
- Let Roman String be ......
Replace string contents of length = 4 with appropriate content
- Length = 4, Roman numerals are
VIII = 8
- Length = 4, Roman numerals are
Replace string contents of length = 3 with appropriate content
- Length = 3, Roman numerals are
MMM = 3000,XXX = 30,VII = 7,III = 3
- Length = 3, Roman numerals are
- Replace string contents of length = 2 with appropriate content
- Length = 2, Roman numerals are
MM = 2000,XX = 20,XI = 11,IX = 9,VI = 6,IV = 4,II = 2
- Length = 2, Roman numerals are
- Once this is done, then follow below rules:
- Subtract digits from each other
Ican be subtracted (absolute) fromVorXXcan be subtracted (absolute) fromLorCCcan be subtracted (absolute) fromDorM
- Finally there will be a bunch of digits. Add all of them to get the answer
- Subtract digits from each other
My questions are :
- Is the algorithm correct ?
- I am planning to optimize the algorithm. Does anyone have any tips ?
I know very well what is an algorithm, and neither I'm interested in giving the codes on Math.SE.
If I'm not wrong in understanding your algo., in those steps of replacing you must keep in mind the precedence of replacement, for example, take $XIX$, you'll first replace XI (as you've typed) with 11, then subtract 10($X$), from 11, thus answer comes 1.
But if you add $XIX$ in the $length=3$ list then you may get the perfect answer.
But, even then, you cannot just write all possible exceptions, 'cause exceptions come due to lack of knowledge or due to improper steps of algorithm. And, due to that "precedence" I said to you that it has a "tint" (only a tint) of programming.
And, just to remove this small flaw($XIX$), you've to take in mind of grouping or at least the correct precedence of replacement.
Well, I found this link of your's very useful. They have the correct precedence.
[EDIT]
Algorithm for it can be recursive in nature and can go like this:
1) Start reading the characters from left.
2) If there is any value you come upon which is less than the earlier value then divide the expression in two, one for left side and one for right side.
3) Find value of left expression using your replace conditions, and repeat the steps for the right side.
4) Finally add all the values.
I checked it for $XIX$ and it works, provided you take the precedence of replacement same as in that link.
[EDIT2]
Well, I found that $V, L, D$ cannot be used as subtracting elements from here and BTW, our algorithms nearly match, why didn't you took a reference from there?