Happy Number

A "Happy Number" is defined as a number that after finite number of "steps" - where we sum the square of each digit each time - the result is a 1. Given a number n, determine whether it is a happy number.

As a challenge, complete this question under constant space.

Parameters

  • n: The number to check.

Result

  • true or false, depending on whether this number is a happy number.

Examples

Example 1

Input: n = 19

Output: true

Explanation:

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Example 2

Input: n = 2

Output: false

Explanation:

2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 18
1^2 + 8^2 = 65
6^2 + 5^2 = 61
6^2 + 1^2 = 37
...

Constraints

  • 1 <= n < 2^31

Try it yourself

Solution

Title

Script

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Contrary to popular belief, Lorem Ipsum is not simply random text.

  >>> a = [1, 2, 3]
  >>> a[-1]
  3

Get premium for instant access to all content and solutions

Upgrade