202. Happy Number

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
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

Constraints:

  • 1 <= n <= 231 - 1

Tags

Two Pointers, Hash Table, Math

Solution

In essential, this problem implies a linked list structure. Thus, we can come up with the idea of using fast and slow pointers to solve it. If faster pointer can reach 1, return true. Otherwise, there is a cycle in this implicit linked list, and we can expect two pointers should meet with each other, then return false.

Complexity

Code

func isHappy(n int) bool {
	step := func(n int) int {
		var sum int
		for m := n; m > 0; m /= 10 {
			sum += (m % 10) * (m % 10)
		}
		return sum
	}
	s, f := n, step(n)
	for f != 1 && s != f {
		s = step(s)
		f = step(step(f))
	}
	return f == 1
}

Reference

Last updated

Was this helpful?