Happy Number

https://leetcode.com/problems/happy-number/

快乐数

 1 class Solution {
 2 public:
 3     bool isHappy(int n) {
 4         int res;
 5         int temp;
 6         unordered_set<int> us;
 7         us.insert(n);
 8         while(true)
 9         {
10             res=0;
11             do
12             {
13                 temp=n%10;
14                 res+=(temp*temp);
15                 n/=10;
16             }while(n!=0);
17             if(res==1)
18                 return true;
19             if(us.find(res) != us.end())
20                 return false;
21             n=res;
22             us.insert(n);
23         }
24     }
25 };

 

posted @ 2015-07-08 10:58  阿怪123  阅读(186)  评论(0编辑  收藏  举报