题目链接: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: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
题目分析:
题目意思就是将一位数的各个位上的数字的平方相加,一直循环上述步骤直至最终稳定在1,则这个数定义为happy num,否则就不是。
一开始一直想不出思考,因为卡在如果一个数不是happy num,那么如何判断它掉入无限循环中呢?后来实在想不出,就去百度关键字happy number,没有看别人的方法,直接看百度百科的解释。看到百度百科的定义里解释比如37就不是,因为它陷入一个循环,马上醒悟过来,感觉估计不是happy num的数会掉入循环中!尽管这时候还有种想法是:万一可能是无限不循环数呢?
我开始码的时候跳过上面的疑问,感觉先不管了,就假设它不会是无限不循环的。写的过程中在想,怎样判断出现了循环?很容易想到的就是用集合set,因为set里的元素是唯一的,于是写法如下:
class Solution {
public:
bool isHappy(int n) {
if (n <= 0) return false;
int tmp = n;
set<int> container;
while (tmp != 1) {
int res = 0;
while (tmp != 0) {
int bit = tmp % 10;
res += bit * bit;
tmp /= 10;
}
if (container.find(res) != container.end())
return false;
else
container.insert(res);
tmp = res;
}
return true;
}
};
过了几天,有突然想起来这道题,觉得用集合有点杀鸡牛刀了,突然想到之前也有一直用的:定义一个标志位数组,用结果数做下标,判断这个数的标志位是否修改过。这种做法适合在结果数在一个比较小的范围,这样就不会浪费太多空间。仔细分析一下,参数n为正整数,类型是int,最大值为2147483647,因此即使找到一个各个位上的平方和最大的,我猜的是1999999999,这个数的各个位的平方和为730,因此初始化的数组不会超过1000,这可以接受。上述分析其实也解释了为什么不可能是无线不循环数,因为平方和是[1, 730],根据抽屉原理,无限次数的循环落在这个区间肯定会有重叠,也就是出现了循环,原疑问check!稍微修改后的代码如下:
class Solution {
public:
bool isHappy(int n) {
if (n <= 0) return false;
int tmp = n;
int flag[750] = { 0 };
while (tmp != 1) {
int res = 0;
while (tmp != 0) {
int bit = tmp % 10;
res += bit * bit;
tmp /= 10;
}
if (flag[res])
return false;
else
flag[res] = 1;
tmp = res;
}
return true;
}
};
比较打脸的是,两份代码在leetcode的测试用例上效率并木有差别,囧rz