Borrar filtros
Borrar filtros

How to sum the digits of a string?

3 visualizaciones (últimos 30 días)
GEORGIOS BEKAS
GEORGIOS BEKAS el 2 de En. de 2018
Respondida: Walter Roberson el 2 de En. de 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))

Respuestas (1)

Walter Roberson
Walter Roberson el 2 de En. de 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.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by