Post

Leetcode 0202. Happy Number

Write an algorithm to determine if a number `n` is happy. A happy number is a number 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 (where it will stay), or it loops endlessly in a cycle which does not include 1.  - Those numbers for which this process ends in 1 are happy. 

Description

Write an algorithm to determine if a number n is happy.

A happy number is a number 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 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
  • 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

Constraints:

  • 1 <= n <= 231 - 1

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    /**
     * Two Pointer with Floyd's cycle-finding
     * (a.k.a. Tortoise and the Hare algorithm)
     * Time Complexity: BigO(n)
     * Space Complexity: BigO(1)
     */
    public boolean isHappy(int n) {
      int slow = n, fast = n;
      do {
          slow = squareSum(slow);
          fast = squareSum(squareSum(fast));

          if (slow == 1) return true;
      } while (slow != fast);
      return false;
    }

    private int squareSum(int num) {
        int sum = 0, newNum = num;
        while (newNum != 0) {
            sum += Math.pow(newNum%10, 2);
            newNum /= 10;
        }
        return sum;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(N)
    def isHappy(self, n: int) -> bool:
        def sumOfSquares(n: int) -> int:
            num = 0
            while n:
                num += (n % 10) ** 2
                n = n // 10
            return num

        lst = set()
        while True:
            if n == 1:
                return True
            elif n in lst:
                return False
            lst.add(n)
            n = sumOfSquares(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Iteration
 * Time Complexity: BigO(N)
 * Space Complexity: BigO(1)
 */
function isHappy(n: number): boolean {
  let fast = n,
    slow = n;

  do {
    fast = sumOfSquares(sumOfSquares(fast));
    slow = sumOfSquares(slow);
  } while (fast !== slow);

  return slow === 1;
}

function sumOfSquares(n: number): number {
  let num = 0;
  while (n !== 0) {
    const dig = n % 10;
    num += dig * dig;
    n = Math.floor(n / 10);
  }
  return num;
}
This post is licensed under CC BY 4.0 by the author.