0

Sololearn practice problem, pls help me with this

During each iteration, the loop uses floor division to divide the given number by 10, thus dropping one digit. The process continues until the number has no more digits (n>0). You need to change the code to calculate and output the sum of all digits of the input number. Sample Input 643 Sample Output 13 Explanation The sum of the digits of 643 is 6+4+3 = 13. n = int(input()) length = 0 while n > 0: n //= 10 length += 1 print(length) Please solve this n = int(input()) length = 0 while n > 0: n %= 10 length += 1 print(length) This not showing any output

11th Dec 2020, 7:10 AM
Abhishek Sinha
Abhishek Sinha - avatar
5 Respuestas
+ 7
Abhishek Sinha your code shows output like Slick said, but it prints the length and not the sum. n%10 gives the last digit. Add that to your result variable (a) in every step and then drop the last digit. Floor division is done with // in Python 3, so the code from Piyush Thourani won't work correctly in Sololearn. Take this instead: n=int(input()) a=0 while n>0: a+=(n%10) n//=10 print(a)
11th Dec 2020, 8:39 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 3
a=0 while n>0: a+=(n%10) n/=10 print(a) Try this and understand the concept
11th Dec 2020, 7:20 AM
Piyush
Piyush - avatar
+ 1
Sanchit Bahl n%10 gibt die letzte Ziffer, z.B. 1234 % 10 = 4 n // 10 gibt die restlichen Ziffern: 1234 // 10 = 123 n//=10 entspricht n = n // 10 Diese brauchen wir im nächsten Schritt, um die nächste Ziffer zur Summe zu addieren
4th Jul 2021, 11:03 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Benjamin Jürgens , Hallo Herr Jürgen, können Sie mir bitte dieses Konzept einmal erläutern, wieso haben Sie " n//=10 " es nochmals eingegeben, wenn wir es schon mit modulo (n%10) gemacht haben ? Ich wäre Ihnen sehr verbunden. Dankeschön im Voraus!
4th Jul 2021, 4:03 PM
Sanchit Bahl
Sanchit Bahl - avatar
- 2
works fine the way its posted. Here it is with default values https://code.sololearn.com/c7N7fwh8Q1oi/?ref=app
11th Dec 2020, 7:25 AM
Slick
Slick - avatar