题目来源
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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
判断一个整数是不是快乐的…最直接的方法就是直接算…用了一个哈希表来存储已经出现过的,假如出现循环节了的话那肯定就不是快乐数了!
class Solution {
public:
bool isHappy(int n) {
unordered_map<int, int> map;
while (n != 1 && !map[n]) {
map[n]++;
int newN = 0;
while (n > 0) {
newN += (n % 10) * (n % 10);
n /= 10;
}
n = newN;
}
if (n == 1)
return true;
else
return false;
}
};
我们用了O(n)的空间,然后又有大神出现了,大吼一声说,渣渣,Floyd你都忘了吗?要你何用!咔嚓,把我干掉了!
实际上也挺简单的,就是设置一个快指针一个慢指针,然后假如有环的话,快指针会追上慢指针,假如没环的话,就到尾巴了,这道题目中的尾巴就是1。
class Solution {
public:
bool isHappy(int n) {
int fast = n, slow = n;
do {
slow = digitSqualSum(slow);
fast = digitSqualSum(fast);
fast = digitSqualSum(fast);
} while (fast != slow && fast != 1);
if (fast == 1)
return true;
else
return false;
}
int digitSqualSum(int n)
{
int newN = 0;
while (n > 0) {
newN += (n % 10) * (n % 10);
n /= 10;
}
return newN;
}
};