LearnFrenzy
Sign in Take a free test

Variables and Data Types · Variables and Data Types Coding Problems · Question 3

Sum and count of digits using arithmetic in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Read a positive integer and print the number of digits and their sum, using only arithmetic (no string conversion).

Solution
main.py Run
n = int(input())
original = n
count = total = 0

while n > 0:
    total += n % 10      # last digit
    n //= 10             # drop the last digit
    count += 1

print(f"{original} has {count} digits, sum = {total}")

Output Verified by running it on Python 3

987654321 has 9 digits, sum = 45

n % 10 extracts the last digit and n //= 10 removes it, until nothing is left.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links