How to sum the digits of a string?

3 次查看(过去 30 天)
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))

回答(1 个)

Walter Roberson
Walter Roberson 2018-1-2
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.

类别

Help CenterFile Exchange 中查找有关 String 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by