Practice › Basics
Digital Root
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Add the digits of n; if the result has more than one digit, add its digits again, and so on until a single digit remains. Print that digit.
n can be very long, so read it as a string.
Input
A single line with the digits of n (no leading zeros unless n is 0).
Output
The digital root of n.
Constraints
- 1 ≤ number of digits ≤ 10^5
The digital root of a positive number is 1 + (n − 1) mod 9 — and n mod 9 equals (sum of digits) mod 9.
Example 1
Input
38
Output
2
Example 2
Input
0
Output
0
Hints
- The number can have 10^5 digits — read it as a string.
- A number and the sum of its digits leave the same remainder when divided by 9.
Approach
Add up the digits once (at most 9 × 10^5). Because digit sums preserve the remainder mod 9, the digital root of a positive number is 1 + (sum − 1) mod 9, and it is 0 only for n = 0. Adding the digits of the sum again until one digit is left gives the same answer.
Complexity: O(number of digits) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
long long sum = 0;
for (char c : s) sum += c - '0';
cout << (sum == 0 ? 0 : 1 + (sum - 1) % 9) << "\n";
return 0;
}Python solution
import sys
s = sys.stdin.readline().strip()
total = sum(map(int, s))
print(0 if total == 0 else 1 + (total - 1) % 9)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
long sum = 0;
for (int i = 0; i < s.length(); i++) sum += s.charAt(i) - '0';
System.out.println(sum == 0 ? 0 : 1 + (sum - 1) % 9);
}
}