202. Happy Number
1. 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.
2. Example
Example 1
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2
Input: n = 2
Output: false
3. Constraints
- 1 <= n <= 2$^{31}$ - 1
4. Solutions
Hash Table
Time complexity: O(logn)
Space complexity: O(logn)
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> value_history;
while (n != 1) {
int sum = 0;
while (n > 0) {
const int mod = n % 10;
sum += mod * mod;
n /= 10;
}
n = sum;
if (value_history.find(n) == value_history.end()) {
value_history.insert(n);
} else {
return false;
}
}
return true;
}
};
Two Pointers
Time complexity: O(logn)
Space complexity: O(1)
class Solution {
public:
bool isHappy(int n) {
int slow = n, fast = get_next(n);
while (fast != 1 && slow != fast) {
slow = get_next(slow);
fast = get_next(get_next(fast));
}
return fast == 1;
}
private:
int get_next(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
};