How to sum the digits of a string?
8 views (last 30 days)
Show older comments
GEORGIOS BEKAS on 2 Jan 2018
Answered: Walter Roberson on 2 Jan 2018
I have created the following program to sum the digits of a number, that derives from the following expression: op = 2^n, where n is an input. What is wrong with the following code:
n = 5
op = 2^n
g = num2str(op)
b = sum(g(1:end))
Walter Roberson on 2 Jan 2018
The characters for the digits start from numeric position 48 in the character charts. So '0' is numeric 48 not 0, and '1' is numeric 49, '2' is numeric 50, and so on. When you sum '32' that is '3'+'2' which is 51+50=101 not 5.
Hint: if you subtract '0' from each position in a string of digits then what is left over is the corresponding decimal value. '32' - '0' = [3 2] which can then be added.
Find more on Characters and Strings 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!