202. Happy Number*
https://leetcode.com/problems/happy-number/
题目描述
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:
Input: 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
C++ 实现 1
基本逻辑很简单, 主要需要考虑无限循环的问题, 比如: 89
:
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
也就是说, 执行基本逻辑的情况下, 最后的结果又等于了初始数据 (89
), 这样造成了无限循环. 因此, 需要使用哈希表记录下每个访问过的数据.
class Solution {
private:
unordered_set<int> record;
public:
bool isHappy(int n) {
int sum = 0;
while (true) {
if (record.count(n)) return false;
record.insert(n);
while (n) {
sum += (n % 10) * (n % 10);
n /= 10;
}
if (sum == 1) break;
n = sum;
sum = 0;
}
return true;
}
};
C++ 实现 2
使用快慢指针, 参考: My solution in C( O(1) space and no magic math property involved )
class Solution {
private:
int digitSquareSum(int n) {
int sum = 0, tmp;
while (n) {
tmp = n % 10;
sum += tmp * tmp;
n /= 10;
}
return sum;
}
public:
bool isHappy(int n) {
int slow, fast;
slow = fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
} while(slow != fast);
return slow == 1;
}
};