国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

20170306-leetcode-202-Happy Number

2019-11-06 06:24:10
字體:
來源:轉載
供稿:網友

1.Description

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following PRocess: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

**Example: **19 is a happy number

12 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1 https://leetcode.com/problems/happy-number/?tab=Description

解讀 給定任何一個正整數,計算每位數上的平方,求和,并不斷重復計算,如果有1出現,則為happyNumber,否則會進入一個循環;所有不快樂數的數位平方和計算,最後都會進入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循環中。 http://baike.baidu.com/link?url=Xc-p5vE0DPUwPkbEj7qeOjTlVSY3TLq-fCUEs-t3gBLQ9DjEWpajg55YCtTP539DABsp6coRd_GCzggVRwA79hsm8dxy4cbIYo3tiGyw8KLXAP6PX-XRio8BfmdbeWc8NZkJKA51b0FMhL7KiYZOjtdA1BTBcbFgc4JZSDcSIxK

2.Solution

class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ stack = [] n=self.caculate(n) stack.append(n) while 1: n=self.caculate(n) if n==1:return True else: if n in stack:return False else: stack.append(n) def caculate(self,n): return sum([int(x)**2 for x in str(n)])

把計算的記過存放在一個stack中,如果中間結果又有1的直接返回true,如果中間結果等于stack中的某一個值,那么返回false

class Solution(object): def isHappy(self, n): n=self.caculate(n) while 1: n=self.caculate(n) if n==1:return True if n==4:return False def caculate(self,n): return sum([int(x)**2 for x in str(n)])

如果計算的過程中有4的出現,那么返回false


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 土默特左旗| 浮山县| 永清县| 海丰县| 永寿县| 武乡县| 秦皇岛市| 克拉玛依市| 礼泉县| 北流市| 阿鲁科尔沁旗| 乐安县| 武胜县| 中阳县| 六盘水市| 临泉县| 卫辉市| 台江县| 吴忠市| 扎赉特旗| 毕节市| 广元市| 无为县| 淳化县| 通道| 都匀市| 曲沃县| 景德镇市| 吉木乃县| 锦屏县| 镇康县| 威信县| 民勤县| 库伦旗| 壶关县| 林芝县| 龙山县| 鹤山市| 江川县| 宁波市| 鹤峰县|