leetcode 202. Happy Number 詳解 python3

一.問題描述

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: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

二.解題思路

判斷是否是Happy Number:

如果每次每個位數平方求和,最後能以1結束,就是快樂數。

如果最後是個循環,就不是。

這道題其實就是考察分離每一個位數。

分離出每一位就是: n mod(%) 10, 就能把個位數分離出來。

然後 n=n/10 把n分離出來的個位數丟掉(其實是已經處理完了不需要了)。

當然你也可以把數字先轉換成字符串,然後再對每個字符轉換成數字,這樣子就不用上面那個。

不過我覺得這樣子應該很慢,你們可以試試,如果這樣更快的話麻煩告訴我。

感覺這種簡單的最好還是自己掌握比較好,畢竟,很多時候其他情況可能不能這樣子取巧或者不適合用哪種方法。

至於考察是否是循環,用一個集合記錄一下之前的每個n。發現現在的n已經在了就說明循環了。

題目比較簡單,就要想想如何寫的簡介.(貌似我老是說這個)。

下面給出了兩種實現,但是第二種快樂4ms至少,主要應該是if 語句減少了。判斷放在while循環判斷了。

更多leetcode算法題解法: 專欄 leetcode算法從零到結束

三.源碼

# version 1
class Solution:
    def isHappy(self, n: int) -> bool:
        if n<0:return False
        is_occured,nxt_n=set(),0
        while True:
            while n:
                nxt_n+=(n%10)**2
                n=int(n/10)
            if nxt_n==1:break
            if nxt_n in is_occured:break
            else:is_occured.add(nxt_n)
            n,nxt_n=nxt_n,0
        return nxt_n==1

# version 2
class Solution:
    def isHappy(self, n: int) -> bool:
        if n<0:return False
        is_occured,nxt_n=set(),0
        while n not in is_occured and n!=1:
            is_occured.add(n)
            while n:
                nxt_n+=(n%10)**2
                n=int(n/10)
            n,nxt_n=nxt_n,0
        return n==1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章