2020年1月22日
Leetcode 202. Happy Number
C++, LeetCode, 算法, 编程
0 Comments
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: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
解析:快乐数,给一个数字n,将每个位置上的数字进行平方求和,循环下去,如果和为1则为快乐数,否则无限循环。首先看一下非快乐数的情况。

由上图可以发现,如果是非快乐数,则后面的数字一直在循环,所以可以设置一个HashSet,将出现的数字存放进去,如果出现重复的则跳出循环,如果为1,则为true。具体代码如下:
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> sets;
int sum = 0;
while(n != 1)
{
sum = get_square_sum(n);
if (sets.count(sum))
break;
sets.insert(sum);
n = sum;
}
return n ==1;
}
int get_square_sum(int n)
{
int sum = 0;
while(n != 0)
{
int single_num = n%10;
sum += pow(single_num, 2);
n /= 10;
}
return sum;
}
};
解法2:
采用检测链表环的思路,这个题目中,数字一定存在部分重复,可以认为是存在环,然后采用链表检测环的思路,使用快慢指针来做。
class Solution {
public:
bool isHappy(int n) {
/**
unordered_set<int> sets;
int sum = 0;
while(n != 1)
{
sum = get_square_sum(n);
if (sets.count(sum))
break;
sets.insert(sum);
n = sum;
}
return n ==1;
**/
int slow, fast;
slow = fast = n;
do
{
slow = get_square_sum(slow);
fast = get_square_sum(fast);
fast = get_square_sum(fast);
}while(slow != fast);
if(slow == 1)
return true;
else
return false;
}
int get_square_sum(int n)
{
int sum = 0;
while(n != 0)
{
int single_num = n%10;
sum += pow(single_num, 2);
n /= 10;
}
return sum;
}
};