題目來源
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
判斷一個整數(shù)是不是快樂的…最直接的方法就是直接算…用了一個哈希表來存儲已經(jīng)出現(xiàn)過的见坑,假如出現(xiàn)循環(huán)節(jié)了的話那肯定就不是快樂數(shù)了婆硬!
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)的空間,然后又有大神出現(xiàn)了暂雹,大吼一聲說策治,渣渣脓魏,F(xiàn)loyd你都忘了嗎?要你何用通惫!咔嚓茂翔,把我干掉了!
實際上也挺簡單的履腋,就是設(shè)置一個快指針一個慢指針珊燎,然后假如有環(huán)的話,快指針會追上慢指針遵湖,假如沒環(huán)的話悔政,就到尾巴了,這道題目中的尾巴就是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;
}
};