Filter löschen
Filter löschen

How to sum the digits of a string?

3 Ansichten (letzte 30 Tage)
GEORGIOS BEKAS
GEORGIOS BEKAS am 2 Jan. 2018
Beantwortet: Walter Roberson am 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))

Antworten (1)

Walter Roberson
Walter Roberson am 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.

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by