Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find the Digital Root

Basic Acceptance 81.53% Points 10.00

You are given a non-negative integer n. Your task is to find its digital root by repeatedly summing its digits until a single digit remains.

At each step, add all the digits of the current number to obtain a new number. Continue this process until the result is a single digit, then return that digit.

Examples
Example 1

Input: n = 12345
Output: 6
Explanation: The sum of the digits is 1 + 2 + 3 + 4 + 5 = 15. Summing again gives 1 + 5 = 6.

Example 2

Input: n = 99
Output: 9
Explanation: The first sum is 9 + 9 = 18. Summing again gives 1 + 8 = 9.

Example 3

Input: n = 0
Output: 0
Explanation: Since 0 is already a single digit, its digital root is 0.

Constraints
  • 0 = n = 10¹8
Companies
Visa Goldman Sachs Qualcomm Coinbase
Topics
Data Structures Basics
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions