Reference: LeetCode
Difficulty: Easy
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 |
Follow up: Use $O(1)$ space.
Analysis
Hash Set
Since you will get repeat numbers again and again, we can put all visited numbers in a hash set to know whether we can stop trying.
I list two ways of writing squareSum()
.
1 | public boolean isHappy(int n) { |
Time: N/A
Space: N/A It depends on the input.
Cycle Detection
We can solve it without extra space.
1 | public boolean isHappy(int n) { |
Time: N/A
Space: $O(1)$