Sum the digits of a number?
123 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi, I'd like to know how can someone add the digits of a number to the final point in matlab.
For example 525 --> 5 + 2 + 5 = 12 --> 1 + 2 = 3
I'm thinking about dividing by ten and adding the digits after the decimal point while at the same time round the number.
Any ideas on how to add the digits would be really helpfull.
Also how to identify a digit by knowing its position in a number
i.e. the 5th digit of 9483672 is 6. Thanks in advance
2 commentaires
Réponses (7)
Les Beckham
le 2 Mai 2020
Modifié(e) : Les Beckham
le 2 Mai 2020
I know it sounds too easy to be true but this manipulation is actually the same as modulo 9. No loops or string conversions needed.
>> mod(525,9)
ans =
3
>> mod(9483672,9)
ans =
3
For the second part of your question, try this:
function [out] = extract_digit(num,digit)
%EXTRACT_DIGIT Return the specified digit from a number
out = num2str(num);
out = out(digit);
end
4 commentaires
John D'Errico
le 6 Avr 2021
@Dimitri Assuming you want to keep on re-summing the digits until the sum is a single digit number... then special case handling still will work. You just need to think about what happens.
The ONLY case where that digit sum is zero is when the number is itself zero. Therefore, if the number is NOT zero, but the modulus was zero, then the digit sum would have been 9.
As such we can see a simple solution:
N = 12345678;
if N == 0
digsum = 0;
else
digsum = mod(N,9);
if digsum == 0
digsum = 9;
end
end
digsum
Is that algorithm correct for N larger than 0? Clearly it works when N == 9. We can write a really simple code to compute the sum of the digits directly, for just one iteration, and then just iterate until it is done.
dsum = @(n) sum(dec2base(n,10) - '0');
digsum = N;
while digsum > 9
digsum = dsum(digsum);
end
digsum
Azzi Abdelmalek
le 17 Jan 2014
a=525;
b=num2str(a);
while numel(b)>1
a=sum(str2double(regexp(b,'\d','match')));
b=num2str(a);
end
out=str2num(b)
% -------------------------------
a=9483672;
b=num2str(a);
b(5)
Ans sadiq
le 19 Août 2021
function out=digit_sum(in)
q=in;
a=q/10;
b=floor(a);
c=q-b*10;
w=c;
if q>0
w=w+digit_sum(b);
end
out=w;
end
0 commentaires
Pablo López
le 5 Fév 2019
You can try this:
n = 525;
sum(str2num(num2str(sum(str2num(num2str(n)')))'))
4 commentaires
Stephen23
le 6 Fév 2019
Modifié(e) : Stephen23
le 6 Fév 2019
The question gave this example:
"For example 525 --> 5 + 2 + 5 = 12 --> 1 + 2 = 3"
which indicates that the 12 digits should also be summed to 3. Usually when this task is given, it is required to continue summing until only one digit is reached (and this is what the other answers do). In contrast, your code sums twice only, regardless of how many digits remain. This may or may not be the intended behavior, it depends entirely on the specifications requested by the assignment. I just wanted to note the distinction.
Image Analyst
le 7 Avr 2021
Here is how I did it:
fprintf('Beginning to run %s.m ...\n', mfilename);
% Get a random integer.
originalNumber = int64(randi(2^53-1, 1, 1))
% Do the first iteration.
strNumbers = num2str(originalNumber);
intNumbers = strNumbers - '0'
loopCounter = 1;
maxIterations = 100; % The Failsafe (so we never get an infinite loop due to a logic error). Every while loop should always have a failsafe.
while length(intNumbers) >= 2 && loopCounter < maxIterations
theSum = sum(intNumbers);
fprintf('After %d iterations, the number is %s and the sum of its digits is %d\n',...
loopCounter, strNumbers, theSum);
% Prepare the next iteration:
strNumbers = num2str(theSum);
intNumbers = num2str(theSum) - '0';
loopCounter = loopCounter + 1;
end
fprintf('Done running %s.m ...\n', mfilename);
I get:
int64
7208285642958972
intNumbers =
7 2 0 8 2 8 5 6 4 2 9 5 8 9 7 2
After 1 iterations, the number is 7208285642958972 and the sum of its digits is 84
After 2 iterations, the number is 84 and the sum of its digits is 12
After 3 iterations, the number is 12 and the sum of its digits is 3
0 commentaires
Javier Echanobe
le 15 Sep 2023
Modifié(e) : Javier Echanobe
le 15 Sep 2023
n=round(1000*rand(1))
SUM=sum(num2str(n))-48*length(num2str(n)) % 48 is the ASCII code for 0
________________
When I execute this code I obtain:
n =
633
SUM =
12
4 commentaires
Dyuman Joshi
le 15 Sep 2023
@Stephen23, I also figured that it does something different.
But from @Javier Echanobe's line "When I execute this code I obtain", I assumed that they were trying to do the same as the original question, but could not achieve it.
Hence my comment.
Javier Echanobe
le 18 Sep 2023
Déplacé(e) : Dyuman Joshi
le 18 Sep 2023
n=round(1000*rand(1))
SUM=sum(num2str(n))-48*length(num2str(n)); % 48 is the ASCII code for 0
while SUM>9
SUM=sum(num2str(SUM))-48*length(num2str(SUM));
end
SUM
You are right.
This code does make it.
Voir également
Catégories
En savoir plus sur Get Started with MuPAD dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!