DSA · Hash Table / Math · #82
Happy Number
Module 65 · difficulty 2/5·⏱ 30:00starts on first keystroke
A **happy number** is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals `1` (happy), or it loops endlessly in a cycle that never reaches `1` (not happy). Implement `isHappy(n)` that returns `true` if `n` is a happy number, and `false` otherwise.
Examples
n = 19→true— 1^2+9^2=82, 8^2+2^2=68, 6^2+8^2=100, 1^2+0^2+0^2=1.n = 2→false— The process enters a cycle (2 -> 4 -> 16 -> 37 -> ... -> 4) and never reaches 1.n = 7→true— 7 -> 49 -> 97 -> 130 -> 10 -> 1.
Constraints
- · 1 <= n <= 2^31 - 1
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.