n= sum([int(i)**2foriinstr(n)])returnn==1 Runtime:60 ms, faster than8.31% of Python3 online submissions for Happy Number. Memory Usage:14 MB, less than20.99% of Python3 online submissions for Happy Number. classSolution:defisHappy(self, n: int) ->bool:whilen> 6: next=0whilen...
1classSolution {2public:3boolisHappy(intn) {4set<int>dict;5while(!dict.count(n)){6dict.insert(n);7intsum =0;8while(n >=1){9sum += (n %10) * (n %10);10n /=10;11}12n =sum;13if(sum ==1)14returntrue;15}16returnfalse;17}18};...
java版本如下所示,方法相同: 1publicclassSolution {2publicbooleanisHappy(intn) {3HashSet<Integer> set =newHashSet<Integer>();4do{5if(set.contains(n))6returnfalse;7set.add(n);8inttmp = 0;9while(n != 0){10tmp += (n%10)*(n%10);11n/=10;12}13n =tmp;14}while(n!=1);15retu...
leetcode 202. Happy Number classSolution {public:boolisHappy(intn) {if(n <=0)returnfalse;set<int>res;while(res.count(n) ==0){ res.insert(n);intnum =0;while(n !=0){ num+= (n%10)*(n%10); n= n/10; }if(num ==1)returntrue; n=num; }returnfalse; } }; count()用来查...
classSolution{public:boolisHappy(intn){ unordered_set<int> visited;while(n !=1&& visited.find(n) == visited.end()){ visited.insert(n);intval =0;while(n >0){intdigit = n %10; val += digit*digit; n /=10; } n = val; ...
1classSolution {2public:3boolisHappy(intn) {4unordered_map<int,int>hashMap;5hashMap[n] =n;6while(n !=1)7{8intsum =0;9inttmpN =n;10while(tmpN !=0)11{12sum += (tmpN %10) * (tmpN %10);13tmpN /=10;14}15n =sum;1617if(hashMap.find(n) !=hashMap.end())18break;19...
LeetCode 202. Happy Number 题目 class Solution { public: map<int,int> mp; bool isHappy(int n) { return fun(n); } bool fun(int n) { if(n==1) return true; else if(mp[n]==1) return false; mp[n]=1; int m=0; while(n) { m+= (n%10)*(n%10); n/=10; } return ...
https://leetcode.com/problems/happy-number/discuss/56913/Beat-90-Fast-Easy-Understand-Java-Solution-with-Brief-Explanation https://leetcode.com/problems/happy-number/discuss/56917/My-solution-in-C(-O(1)-space-and-no-magic-math-property-involved-) ...
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> To...
classSolution{public:boolisHappy(intn){unordered_set<int> lookup;while(lookup.find(n)==lookup.end()){ lookup.insert(n); n = getNext(n);if(n==1)returntrue; }returnfalse; }intgetNext(intn){inta =0;intr =0;while(n!=0){