使用哈希表来进行循环检测,如果出现了循环,则返回false

    1. class Solution {
    2. public:
    3. unordered_map<int,int> hash;
    4. int fun(int x){
    5. int res = 0;
    6. while(x){
    7. res += (x%10)*(x%10);
    8. x /= 10;
    9. }
    10. return res;
    11. }
    12. bool isHappy(int n) {
    13. int t = n;
    14. while(t != 1&& !hash[t] ){
    15. hash[t]++;
    16. t = fun(t);
    17. }
    18. return t==1;
    19. }
    20. };