Happy number란 ?
주어진 인수의 각 자리수의 제곱의 합을 구하고
그 값이 1이면 happy number이고 아닐경우, 과정을 반복합니다.
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
//problem no : 202
class Solution {
public:
int calHappy(int n){
int ans = 0;
while(n > 0){
int i = n%10;
ans += i*i;
n /= 10;
}
return ans;
}
bool isHappy(int n) {
int happyNum = calHappy(n);
set<int> myset;
pair<set<int>::iterator,bool> p;
while(happyNum != 1){
p = myset.insert(happyNum);
if(p.second == false){
return false;
}
happyNum = calHappy(happyNum);
}
return true;
}
};
endless로 도는 부분을 어떻게 찾아낼까?
전에 풀었던 slow, fast 개념을 적용하면 쉽게 풀 수 있었을 것 같습니다.