(leetcode) Happy Number
1 class Solution { 2 public: 3 int calculate(int n) 4 { 5 int res = 0; 6 while(n > 0) 7 { 8 int tmp = n%10; 9 res = res + tmp*tmp; 10 n /= 10; 11 } 12 return res; 13 } 14 bool isHappy(int n) { 15 if(n == 1) return true; 16 unordered_set<int> Tocheck; 17 while(n) 18 { 19 int tmp = calculate(n); 20 if(1 == tmp) return true; 21 else 22 { 23 if(Tocheck.find(tmp) != Tocheck.end()) 24 return false; 25 else 26 Tocheck.insert(tmp); 27 } 28 n = tmp; 29 } 30 } 31 };

浙公网安备 33010602011771号