Write a script/function that converts a Roman numeral to its decimal equivalent.
ID: 3530701 • Letter: W
Question
Write a script/function that converts a Roman numeral to its decimal equivalent. There are two distinct situations that you might design your program for: a. The "old" style where the order of the symbols does not matter. In this case, IX and XI both mean 10 + 1 or 11. You should be able to handle the following conversion table: Roman Decimal I 1 V 5 X 10 L 50 C 100 D 500 M 1000 b. The "new" style where the order of the symbols does matter. For example, IX is 9 (10 - 1), XC is 90 (100 - 10). The conversion table given above still holds and you may assume for this case that the only instances of "order" you will encounter are IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900) The function input will be useful here. The format >> str = input('Roman numeral: ','s') will provide a way to get the Roman number into your program as a string. It would be a good idea to try case a. first.Explanation / Answer
As the new roman usage indicate (this was the only usage I have learn at
school), the value of the roman symbol is add or substrat depending of the
relative position in the string compare to other symbol of any higher
values.
Please note that these function also are valid for longer roman string than
two caracters. No validity checking is made, nor conversion of lower to
upper case, unvalid string ends the functions in error...
"no carriage return"
============================================================================
=======
function N=oldroman( t_rom );
% Convert old roman style text string number
% Constant
Symb=['IVXLCDM'];
Valu=[1 5 10 50 100 500 1000];
% Intit return value
N=0;
for i=1:length(t_rom)
p=findstr(t_rom(i),Symb);
N=N+Valu(p);
end
==================================================================
function N=newroman( t_rom );
% Convert old roman style text string number
% Constant
Symb=['IVXLCDM'];
Valu=[1 5 10 50 100 500 1000];
% Intit return value
N=0;
for i=1:length(t_rom)
P(i)=findstr(t_rom(i),Symb);
end
for i=1:length(t_rom)
if any(P(i+1:end)>P(i))
N=N-Valu(P(i));
else
N=N+Valu(P(i));
end
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.