leet code 1131 - Happy Number C++. time beats 0%, space beats 24.85% 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37class Solution { public: bool isHappy(int n) { vector<int> a[10000]; while(true) { int nextN = calcHappy(n); if(nextN==1) return true; if(a[nextN%10000].size()) { bool result=true; for(int i=0; i<a[nextN%10000].size(); ++i) { if(a[nextN%10000][i] == nextN) { return false; } } } a[nextN%10000].push_back(nextN); n = nextN; } } int calcHappy(int n) { int result = 0; while(n) { result += (n%10)*(n%10); n /= 10; } return result; } };