202. Happy Number 快樂數
阿新 • • 發佈:2018-11-30
- 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:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
編寫一個演算法來判斷一個數是不是“快樂數”。
一個“快樂數”定義為:對於一個正整數,每一次將該數替換為它每個位置上的數字的平方和,然後重複這個過程直到這個數變為 1,也可能是無限迴圈但始終變不到 1。如果可以變為 1,那麼這個數就是快樂數。
示例:
輸入: 19
輸出: true
解釋:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
解題思路:這道題的關鍵在於怎麼判斷不是happy數,不是happy數算下來會一直迴圈,所以只要判斷每個位置上的數的平方和已經出現過,就可以。
程式碼C++:
class Solution {
public:
bool isHappy(int n) {
unordered_map < int , int > ha;
int t =0;
while( t != 1)
{
if(ha.count(n))
return false;
ha[n] = 1;
t =0;
while(n)
{
t +=pow(n%10, 2);
n/=10;
}
n = t;
}
return true;
}
};