Description
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
My solution
class Solution {
public:
bool isHappy(int n) {
int sum;
int rear;
vector<int> set;
while (n) {
set.push_back(n);
sum = 0;
while (n) {
rear = n % 10;
sum += rear * rear;
n /= 10;
}
n = sum;
if (n == 1) return true;
// 这里有待改进
for (int i = 0; i < set.size(); i++) {
if (n == set[i]) return false;
}
}
}
};
问题关键地方是在陷入循环的时候跳出来, 自然的想法是开辟一个数组, 存储出现过的值, 对于每个新生成的数值, 检查数组中是否已经存在该值. 我的代码中采取的方式效率较低. discuss中表示这一步替换成Hash方式!! 类似于python中的dict形式.
参考如下:
public boolean isHappy(int n) {
Set<Integer> inLoop = new HashSet<Integer>();
int squareSum,remain;
while (inLoop.add(n)) {
squareSum = 0;
while (n > 0) {
remain = n%10;
squareSum += remain*remain;
n /= 10;
}
if (squareSum == 1)
return true;
else
n = squareSum;
}
return false;
}
Discuss
发现一个神思路: 循环检测, 其实就等同于图中的环的检测. 之前做链表中环的检测做法是用两个指针, 一个walker, 一个runner(或者slower和faster), 这里再次利用这个方式(时间换取空间), 形成如下思路:
I see the majority of those posts use hashset to record values. Actually, we can simply adapt the Floyd Cycle detection algorithm. I believe that many people have seen this in the Linked List Cycle detection problem. The following is my code:
int digitSquareSum(int n) {
int sum = 0, tmp;
while (n) {
tmp = n % 10;
sum += tmp * tmp;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int slow, fast;
slow = fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
} while(slow != fast);
if (slow == 1) return 1;
else return 0;
}
// 注意!!
// 上述代码采用do-while结构,如果直接用while, 因为初始值原因, 很尴尬!!
// 用如下的方式略臃肿...
// 这个细节很微妙
while(walker!=1){
walker = cal(walker);
runner = cal(runner);
runner = cal(runner);
if(walker==runner) break;
}
return walker==1;
细想来, 可以把每次运算的结果视为一个状态, 整个计算流程实际上就是不同状态之间的转换, 状态转换看起来就是图的形式, 故而可以联想到链表中环路检测方法.