Skip to the code
cf.
+10 XP

#238 Digit Square Streak

easy

A game awards a "lucky score" badge with this rule: replace the score by the sum of the squares of its digits, and repeat. If the number ever becomes 1, the score is lucky. If it never does, it goes round the same numbers forever. For example 19 gives 1 + 81 = 82, then 64 + 4 = 68, then 36 + 64 = 100, then 1.

Write isLuckyScore(n) that returns true if n is lucky and false otherwise. Since a number that is not lucky loops forever, you need a way to notice the loop.

Example 1

Input: n = 19
Output: true

19 -> 82 -> 68 -> 100 -> 1.

Example 2

Input: n = 2
Output: false

2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4, and 4 was already seen, so it loops forever.

Constraints

  • 1 <= n <= 2^31 - 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).