Digital Root of a Numeric String
Updated
Problem statement
You are given a string num that holds a non-negative whole number written in decimal. The number can be much too long to fit in any built-in integer type.
Add up the digits of the number. If that sum has more than one digit, add up the digits of the sum. Keep going until only one digit is left, and return that digit. This digit is called the digital root of the number.
Leading zeros in num do not change the number. If every digit is 0, the number is zero and the answer is 0.
Follow-up: once you have the sum of the digits, can you get the answer with a single formula instead of a loop?
Function
digitalRoot(num: String) → intExamples
Example 1
num = "28"return = 1The digits of "28" add up to 2 + 8 = 10. That has two digits, so add again: 1 + 0 = 1. One digit is left, so the answer is 1.
Example 2
num = "0099999"return = 9The leading zeros add nothing. The digits add up to 45, then 4 + 5 = 9, so the answer is 9.
Example 3
num = "000"return = 0Every digit is 0, so the sum is 0, which is already one digit. The answer is 0.
Constraints
1 <= num.length <= 10^4numconsists only of the digits'0'to'9'. It may start with zeros.
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Roman to IntegerKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Palindrome Match PercentageApple · ONSITE INTERVIEWApple interview questions
- Caesar Cipher with a Precomputed AlphabetAmazon · ONSITE INTERVIEW
- Add Two Binary StringsPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Most Cost-Effective MachineCapital One · ONSITE INTERVIEWCapital One interview questions
- Add Two Numeric Strings with CarryZipRecruiter · ONSITE INTERVIEWZipRecruiter interview questions
- Substrings Made Only of VowelsExpedia · ONSITE INTERVIEWExpedia interview questions
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Iterate Canonical IPv6 AddressesOpenAI · ONSITE INTERVIEWOpenAI interview questions
- Nth Staged License PlateGoogle · ONSITE INTERVIEWGoogle interview questions