LeetCode 202 -- python 计算 happy number
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 202 -- python 计算 happy number
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一篇貢獻給python計算happy number~
?
def cal(n):s=str(n)sum=0for i in range(len(s)):sum+=int(s[i])**2return suma=77 # 13 139 ok; 4 5 6 not # print (cal(a)) def itr(a):log_set=set([a])while a!=1:temp = cal(a)if temp in log_set:return False # False but not falseelse:log_set.add(temp)a=temp # lost as testing onlinereturn Trueprint ("itr(a): ",itr(a))?
一個非常慢的方法
class Solution(object):def isHappy(self, n):""":type n: int:rtype: bool"""def cal(n):s=str(n)sum=0for i in range(len(s)):sum+=int(s[i])**2return sumlog_set=set([])while n!=1:temp = cal(n)if temp in log_set:return Falseelse:log_set.add(temp)n=temp # lost as testing onlinereturn True?
轉載于:https://www.cnblogs.com/gils-pumpkin/p/10934384.html
總結
以上是生活随笔為你收集整理的LeetCode 202 -- python 计算 happy number的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 李子柒旗下产品被指吃出烟头 网红带货真该
- 下一篇: 利息多少算高利贷