代码(Python3) class Solution: def isHappy(self, n: int) -> bool: # used 维护已出现的数字集合 used: Set[int] = set() #当 n 未出现过时,继续计算下一个数 while n not in used: # 标记 n 已出现过 used.add(n) # 计算下一个数,即求 n 的每一位的平方和 nxt: int = 0 #当 n ...
LeetCode 202 -- python 计算 happy number 第一篇贡献给python计算happy number~ defcal(n): s=str(n) sum=0foriinrange(len(s)): sum+=int(s[i])**2returnsum a=77#13 139 ok; 4 5 6 not#print (cal(a))defitr(a): log_set=set([a])whilea!=1: temp=cal(a)iftempinlog_set:ret...
classSolution:defisHappy(self, n: int) ->bool:whilen> 6: 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:...
设了个集合来检查是否有中间结果 class Solution: def isHappy(self, n: int) -> bool: def cal_happy(n): sum = 0 while n: sum += (n%10)**2 n = n//10 return sum mid_result = {n} while True: n = cal_happy(n) if n==1: return True if n in mid_result: return False els...
《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 代码。简体版和繁体版同步更新,English version ongoing - hello-algo/mkdocs.yml at main · do-happy/hello-algo
October1_leetcode.cpp Palindrom.cpp Print.py Prob_C.cpp README.md ReverseNumber.java SelectionSort.cpp Simpleform.html SparseMatrix.cpp StructuredArray.cpp Sum_complex_number.py Swaping.py The Coin change prob solution ThreeSumZero.java
Happy Number 快乐数(Easy)(JAVA) 题目地址: https://leetcode.com/problems/happy-number/ 题目描述: Write an algorithm to determine if a number n is “happy”. A happy number is a number def...lintcode-easy-Number of Islands Given a boolean 2D matrix, find the number of islands. Given...
【LeetCode】 Longest Common Prefix 【Python || C++】 题目: 最长的前缀公共子字符串 Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Example 2: &nb......
链接:https://leetcode-cn.com/problems/happy-number 方法: 方法一:哈希表法-可以收敛到1,肯定是有限迭代,否则一定进入循环 方法二:快慢指针-类似环形链表快慢指针相遇问题 python # 0202.快乐数 classSolution: defisHappy(self,n:int)->bool: """ ...
https://leetcode.com/discuss/33014/4ms-5-line-c-code bool isHappy(int n) { while(n>6){ int next = 0; while(n){next+=(n%10)*(n%10); n/=10;} n = next; } return n==1; } 两个python代码: def isHappy(self, n): ...