0202. Happy Number

202. Happy Number #

Problem #

Write an algorithm to determine if a number 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, and 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 numbers.

Example 1:


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

Problem Summary #

Determine whether a number is a “happy number”. The definition of a “happy number” is: continuously add up the squares of each digit of the number, repeating this process. If the result can eventually be 1, then it is a “happy number”; if it cannot reach 1 and a cycle appears, then output false.

Solution Approach #

Just follow the requirements of the problem statement.

Code #


package leetcode

func isHappy(n int) bool {
	record := map[int]int{}
	for n != 1 {
		record[n] = n
		n = getSquareOfDigits(n)
		for _, previous := range record {
			if n == previous {
				return false
			}
		}
	}
	return true
}

func getSquareOfDigits(n int) int {
	squareOfDigits := 0
	temporary := n
	for temporary != 0 {
		remainder := temporary % 10
		squareOfDigits += remainder * remainder
		temporary /= 10
	}
	return squareOfDigits
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文