Write a MATLAB (Octave) function roman2num(s) that converts a Roman numeral to a
ID: 3731673 • Letter: W
Question
Write a MATLAB (Octave) function roman2num(s) that converts a Roman numeral to a number.
Instructions:
i) The numeral is contained in the string s and is capitalized.
ii) You can assume that s is a valid input without checking it.
iii) The characters that appear in the string s are specified in the left column of the table below.
iv) Each character has a "value" according to the table.
v) If the characters to the right of the given character have a value less then the character value - then it's value is added to the sum. Otherwise, it is subtracted.
numeral value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Examples :
>>roman2num('II')
2
>>roman2num('XLIII')
43
More examples - in the Wikipedia article: http://en.wikipedia.org/wiki/Roman_numerals
Please be as simple as possible and complete in full.
Explanation / Answer
function [x]=roman2decimal(s)
s1=substring(s,1,1);
s2=substring(s,2,2);
s=substring(s,3,numel(s));
x=0;
while(s1~='')
% case 1 - if any of these conditions are true
if(s1=='C' and s2=='M') x=x+900;
if(s1=='C' and s2=='D') x=x+400;
if(s1=='X' and s2=='C') x=x+90;
if(s1=='X' and s2=='L') x=x+40;
if(s1=='I' and s2=='X') x=x+9;
if(s1=='I' and s2=='V') x=x+4;
compute new s1, s2 and s;
% case 2 - no case 1 conditions were true
if(s1=='M') x=x+1000;
if(s1=='D') x=x+500;
if(s1=='C') x=x+100;
if(s1=='L') x=x+50;
if(s1=='X') x=x+10;
if(s1=='V') x=x+5;
if(s1=='I') x=x+1;
s1=s2, compute new s2 and new s;
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.