If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. Write a function called number2letters that returns the number of letters needed to write down the number n in
31 views (last 30 days)
Show older comments
function t=number2letters(n)
number2letters(1)=3;
number2letters(2)=3;
number2letters(3)=5;
number2letters(4)=4;
number2letters(5)=4;
number2letters(6)=3;
number2letters(7)=5;
number2letters(8)=5;
number2letters(9)=4;
number2letters(13)=3;
number2letters(11)=6;
number2letters(12)=6;
number2letters(13)=8;
number2letters(14)=8;
number2letters(15)=7;
number2letters(16)=7;
number2letters(17)=9;
number2letters(18)=8;
number2letters(19)=8;
number2letters(20)=6;
number2letters(30)=6;
number2letters(40)=5;
number2letters(50)=5;
number2letters(60)=5;
number2letters(70)=7;
number2letters(80)=6;
number2letters(90)=6;
number2letters(100)=10;
number2letters(200)=10;
number2letters(300)=12;
number2letters(400)=11;
number2letters(500)=11;
number2letters(600)=10;
number2letters(700)=12;
number2letters(800)=12;
number2letters(900)=11;
for n=(1:999)
if (2<= log10(n))&& (log10(n)<3)
b=floor(x/100);
c=fix(mod(x,100)/10);
d=mod(mod(x,100),10);
t=number2letters(b)+10+number2letters(c)+number2letters(d);
elseif (1<= log10(n))&& (log10(n)<2)
c=fix(mod(x,100)/10);
d=mod(mod(x,100),10);
t=number2letters(c)+number2letters(d);
else
t= number2letters(n);
end
end
end
6 Comments
Stephen23
on 27 Aug 2018
Edited: Stephen23
on 27 Aug 2018
@Lisa SU: do NOT name any variable inside the function with the same name as the function itself. This is a guaranteed path to confusing code and strange bugs.
@madhan ravi: perhaps n=5 for the example given in the question, but I agree that this is not really very clear: is the function supposed to calculate the sum from 1:n, as the example shows, or just for n?
madhan ravi
on 27 Aug 2018
Edited: madhan ravi
on 27 Aug 2018
@Stephen cobeldick thank you neither do I understand the question.According to what I understand is for example n = 5 when this function is called the output should be 4 because it consists of four letters. I have a clue that it has something to do with strings or cells because inputs are characters such as five.
Answers (1)
Pierre845
on 27 Aug 2018
Do a Switch .. Case it will be much cleaner.
Also, your function cannot work as you need conditional statements (if .. elseif ..)
function result = number2letters(n) switch n case 1 result = 3; case 2 result = 3; case 3 result = 5; % etc .. end
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!