[leetcode]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. 快乐数
2. 无限循环不快乐数
3. 无限不循环不快乐数

普通解法

class Solution {
public:
bool isHappy(int n) {
set<int> s;
while (n != 1) {
int temp = 0;
while (n) {
temp += (n % 10) * (n % 10);
n /= 10;
}
n = temp;
if (s.count(n)) break;
else s.insert(n);
}
return n == 1 ? true : false;
}
};


难得一见的解法

leetcode 偶然得到的代码，不去做 set 查重，而是设立两个速度不一样的 slow， fast 中间值，中间值追击相遇了，说明要么结果为 1，要么陷入循环。

class Solution {
int calcSum(int n){
int sum = 0;
while(n){
int num = n % 10;
sum += num * num;
n /= 10;
}
return sum;
}
public:
bool isHappy(int n) {
int slow = n, fast = n;
do{
slow = calcSum(slow);
fast = calcSum(fast);
fast = calcSum(fast);
} while(slow != fast);

return slow == 1 ? true : false;
}
};


第三种解法

class Solution {
public:
bool isHappy(int n) {
while (n != 1 && n != 4) {
int t = 0;
while (n) {
t += (n % 10) * (n % 10);
n /= 10;
}
n = t;
}
return n == 1;
}
};


[最后一种方法来源][https://discuss.leetcode.com/topic/12587/my-solution-in-c-o-1-space-and-no-magic-math-property-involved]