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_number = n;
int fast_number = get_next_number(n);
while (fast_number != 1 && slow_number != fast_number) {
slow_number = get_next_number(slow_number);
fast_number = get_next_number(get_next_number(fast_number));
}
return fast_number == 1;
}
private:
int get_next_number(int n) {
int digit_sum = 0;
for (; n > 0; n /= 10) {
int digit = n % 10;
digit_sum += digit * digit;
}
return digit_sum;
}
};