# 【LeetCode】 202. Happy Number ## 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. > 寫一個演算法,找出一個數字是不是"快樂的"。 > 一個快樂數由以下程序來決定:給予一個正整數,不停地將該正整數替換成自身每個位數的平方和,如果最後他變成"1"(然後就會一直維持在"1"),該數字就是快樂數;否則它可能會卡在某個不是1的數列中循環,那該數字就不是快樂數。 ## Example: ``` Example: Input: 19 Output: true Explanation: 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 ``` ## Solution * 兩種做法: * 第一種作法是我的作法(下方的Code),在不知道非1的循環的組成時,暴力地將數字跑很多次function,如果它是快樂數,它就有很高的可能會落在`1`。 * 第二種作法:如果去觀察不跑到`1`的情況,你會發現一定會跑到`4`,簡單列出幾個: * 2 > 4 > 16 > 37 > 58 > 89 > 145 > 42 > 20 > 4 * 3 > 81 > 65 > 61 > 37 * 5 > 25 > 29 > 85 > 89 * 6 > 36 > 45 > 41 > 17 > 50 > 25 * 所以你的ForLoop就不用用無腦跑,而是判斷跑到`1`或是`4`出現即可。 ### Code ```C++=1 class Solution { public: int HappyNumber(int n) { int ans=0; while(n>0) { int temp = n % 10; ans += pow(temp,2); n /= 10; } return ans; } bool isHappy(int n) { for(int i = 0;i < 100 ;i++) n = HappyNumber(n); return n == 1; } }; ``` ###### tags: `LeetCode` `C++`