Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
Getting sum of digits in a number with a while loop.
Code: num = 123 sum = 0 while n > 0: sum += n % 10 n //= 10 print(sum) Question: How do we get last digit to the left (1 in 123)? I understand how we get (3 + 2) but not (3+2+1). Can someone explain in a visible way? Thanks.
5 Respostas
+ 6
First it will get the remainder by using modulus operator (%) to a number by 10, in other words it will get the last digit.
ā«ļøe.g. 123 % 10 ---> 3
Then after we get the last digit, we will use floor division (//) and divide it by 10 to remove the last digit.
ā«ļøe.g. 123 // 10 ---> 12
Then repeat the process until we have no digits left or 0.
__________________________
INPUT = 123
ā¹ļø---FIRST LOOP---ā¹ļø
š¹123 % 10 ---> 3 (add to sum)
š¹123 // 10 ---> 12 (last digit '3' removed)
šøsum is now 3
šøn is now 12
ā¹ļø---SECOND LOOP---ā¹ļø
š¹12 % 10 ---> 2 (add to sum)
š¹12 // 10 ---> 1 (last digit '2' removed)
šøsum is now 5
šøn is now 1
ā¹ļø---THIRD LOOP---ā¹ļø
š¹1 % 10 ---> 1 (add to sum)
š¹1 // 10 ---> 0
šøsum is now 6
šøn is now 0
_______š»BREAKš»________
Since n is now 0 the while loop condition will become False and the loop will end or break.
And the final value of n is 6.
Therefore the sum of digits in 123 is 6.
If this is still unclear, please feel free to ask. Thanks.
+ 4
Actually this program is used to reverse a given number. So here it is
Actually it will be
Rev = n % 10
But now sum += n%10
I hope it is clear to you
+ 2
n= 123
sum = 0
while n > 0:
sum += n % 10
n //= 10
print(sum)
+ 1
Just write n instead of num in declaration or vice versa
0
Cyan Great way of answering.
I had to google how 1 is the remainder after 1 is divided by 10.
Proof:
dividend = (divisor x quotient) + remainder.
1 = (10 x 0) + 1