Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set.

Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set.
def happy(n):
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n); n = sum(int(d) ** 2 for d in str(n))
    return n == 1
print(happy(19), happy(2), happy(7))
What is printed?
  1. A. True False False
  2. B. True False True
  3. C. True True True
  4. D. False False True

Correct answer: B. True False True

19 → 82 → 68 → 100 → 1 (happy). 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, a cycle (not happy). 7 → 49 → 97 → 130 → 10 → 1 (happy).

More Coding Interview Problems questions

Exams that ask this topic