Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital root).

Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital root).
def root(n): return 0 if n == 0 else 1 + (n - 1) % 9
print(root(38), root(999999999), root(0), root(10**18 + 7))
What is printed?
  1. A. 2 0 0 8
  2. B. 11 9 0 8
  3. C. 2 9 1 8
  4. D. 2 9 0 8

Correct answer: D. 2 9 0 8

A number is congruent to its digit sum mod 9, so the repeated digit sum is 1 + (n − 1) mod 9 for n > 0. 38 → 11 → 2. A multiple of 9 gives 9, not 0 (n % 9 would wrongly give 0). 10¹⁸ + 7 → 1 + 7 = 8. O(1).

More Coding Interview Problems questions

Exams that ask this topic