Tutorialspoint
Problem
Solution
Submissions

Sum of the Digits

Certification: Basic Level Accuracy: 22.22% Submissions: 9 Points: 5

Write a C++ program that repeatedly sums the digits of a number until the result is a single digit.

Example 1
  • Input: number = 9875
  • Output: 2
  • Explanation:
    • Step 1: Sum the digits of 9875: 9 + 8 + 7 + 5 = 29.
    • Step 2: Since 29 is not a single digit, sum its digits: 2 + 9 = 11.
    • Step 3: Since 11 is not a single digit, sum its digits: 1 + 1 = 2.
    • Step 4: Since 2 is a single digit, return 2 as the final result.
Example 2
  • Input: number = 12345
  • Output: 6
  • Explanation:
    • Step 1: Sum the digits of 12345: 1 + 2 + 3 + 4 + 5 = 15.
    • Step 2: Since 15 is not a single digit, sum its digits: 1 + 5 = 6.
    • Step 3: Since 6 is a single digit, return 6 as the final result.
Constraints
  • 1 ≤ number ≤ 10^9
  • Time Complexity: O(log(n))
  • Space Complexity: O(1)
NumberControl StructuresDeloitteSwiggy
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

  • Use a loop to sum the digits of the number.
  • Repeat the process until the sum is a single digit.
  • Handle edge cases where the number is already a single digit.

Steps to solve by this approach:

 Step 1: Define a function sum_of_digits that takes an integer.

 Step 2: Use an outer while loop that continues until the number is a single digit (less than 10).
 Step 3: Initialize a sum variable to 0.
 Step 4: Use an inner while loop to extract each digit and add it to the sum.
 Step 5: Update the number with the calculated sum.
 Step 6: Return the single-digit number (digital root).

Submitted Code :