フィルターのクリア

How to sum the digits of a string?

3 ビュー (過去 30 日間)
GEORGIOS BEKAS
GEORGIOS BEKAS 2018 年 1 月 2 日
回答済み: Walter Roberson 2018 年 1 月 2 日
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 Center および File ExchangeString についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by