09 · Math & Number Theory

#202 Happy Number

Easysolve on LeetCode ↗

frequently reported atAirbnbGoogleAmazonApple

the problem

In plain words

Start from a positive int n and keep replacing it with the sum of the squares of its digits. If this ever reaches 1, n is happy. If it loops forever without reaching 1, it isn't. Return whether n is happy.

in n = 19

out true

1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1.

in n = 2

out false

2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → … a loop without 1.

  • 1 ≤ n ≤ 2³¹ − 1

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #141
      Linked List Cycle
      Easyin Linked Lists
    2. #7
      Reverse Integer
      Mediumin Math & Numbers