題目鏈接:https://leetcode.com/problems/happy-number/
題目理解:實現isHappy函數,判斷一個正整數是否為happy數
happy數:計算要判斷的數的每一位的平方和,平方和為1則為happy數,不為1則將原數替換為此平方和,繼續上述步驟,直到等於1(為happy數),或者進入不包含1的無限循環(非happy數)。
測試用例:19為happy數:
1 class Solution {
2 public:
3 bool isHappy(int n) {
4 set<int> result;
5 int re = 0;
6 while(n!=1&&!result.count(n)){
7 result.insert(n);
8 re = 0;
9 while(n){
10 int a = n%10;
11 re+=a*a;
12 n = n/10;
13 }
14 n = re;
15 }
16 if(n==1) return true;
17 else return false;
18 }
19 };
View Code
卡住的點: