Tutorialspoint
Problem
Solution
Submissions

Find the Sum of Digits in a Number

Certification: Basic Level Accuracy: 50.47% Submissions: 537 Points: 5

Write a Python program that calculates the sum of all digits in a given integer.

Example 1
  • Input: 12345
  • Output: 15
  • Explanation:
    • Step 1: Take the digit 5 (12345 % 10 = 5). Sum = 5.
    • Step 2: Remove the last digit (12345 // 10 = 1234).
    • Step 3: Take the digit 4 (1234 % 10 = 4). Sum = 5 + 4 = 9.
    • Step 4: Remove the last digit (1234 // 10 = 123).
    • Step 5: Take the digit 3 (123 % 10 = 3). Sum = 9 + 3 = 12.
    • Step 6: Remove the last digit (123 // 10 = 12).
    • Step 7: Take the digit 2 (12 % 10 = 2). Sum = 12 + 2 = 14.
    • Step 8: Remove the last digit (12 // 10 = 1).
    • Step 9: Take the digit 1 (1 % 10 = 1). Sum = 14 + 1 = 15.
    • Step 10: No more digits left, return the sum 15.
Example 2
  • Input: -678
  • Output: 21
  • Explanation:
    • Step 1: Convert to positive number. -678 becomes 678.
    • Step 2: Take the digit 8 (678 % 10 = 8). Sum = 8.
    • Step 3: Remove the last digit (678 // 10 = 67).
    • Step 4: Take the digit 7 (67 % 10 = 7). Sum = 8 + 7 = 15.
    • Step 5: Remove the last digit (67 // 10 = 6).
    • Step 6: Take the digit 6 (6 % 10 = 6). Sum = 15 + 6 = 21.
    • Step 7: No more digits left, return the sum 21.
Constraints
  • -10^9 ≤ number ≤ 10^9
  • For negative numbers, ignore the negative sign
  • Time Complexity: O(log n), where n is the input number
  • Space Complexity: O(1)
NumberFunctions / MethodsFacebookAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Convert to string and iterate: sum(int(digit) for digit in str(abs(number)))
  • Use modulo and division: while number > 0: sum += number % 10; number //= 10
  • Use recursion: def sum_digits(n): return 0 if n == 0 else abs(n) % 10 + sum_digits(abs(n) // 10)
  • Use map(): sum(map(int, str(abs(number))))

The following are the steps to find the sum of digits in a number:

  • Create a function sum_of_digits that takes a number n as input.
  • Handle the case of negative numbers by converting to positive (using abs(n)).
  • Initialize a variable digit_sum to 0 to store the running sum.
  • Extract each digit from the number using a loop:
    • Use the modulo operator (%) to get the last digit: digit = n % 10
    • Add this digit to the running sum: digit_sum += digit
    • Remove the last digit from the number using integer division: n //= 10
    • Continue this process until no digits remain (n becomes 0)
  • Return the final sum.

Submitted Code :