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?- A. True False False
- B. True False True
- C. True True True
- 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
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…
- A suffix array of a string of length n is built by putting all suffixes in a list and sorting them with a comparison sort, where each…
- What is the solution of T(n) = T(n/2) + T(n/4) + n?
- Edge case: Java's int arithmetic wraps around in two's complement. The Python code below emulates exactly what this Java line computes…
- Edge case: Array sorting and parseInt in JavaScript. javascript console.log([3, 20, 100].sort().join(","), [1, 2…
- Problem: Answer sub-rectangle sum queries on a matrix in O(1) each with a 2-D prefix-sum table. python m = [[3, 0, 1, 4], [5, 6, 3, 2]…