class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ stack<int> stk; set<int> looptest; stack<int> extract(int n){ stack<int> s; while(n){ s.push(n%10); n/=10; } return s; } int happysum(stack<int> s){ long long sum=0; while(!s.empty()){ sum+=(s.top()*s.top()); s.pop(); } return sum; } bool happynum(int n) { // write code here looptest.insert(n); int sum = n; while(true){ stk=extract(sum); sum=happysum(stk); if(sum==1) return true; if(!looptest.count(sum)){ looptest.insert(sum); }else{ return false; } } return true; } };
进入循环则不是快乐数。函数里尽量用局部栈局部变量...不然bug多。