2023年5月20日 星期六

5/20 每日一題 (對各個位數的平方和相加)

 Write an algorithm to determine if a number n is happy.

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.
  • 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.

Return true if n is a happy number, and false if not.

 

Example 1:

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

Example 2:

Input: n = 2
Output: false

 

Constraints:

  • 1 <= n <= 231 - 1


這個題目藉由迴圈來找出使否 各位數的數字的平和加總 是否會等於1

所以關鍵在於 如何避免陷入無窮迴圈的狀況

試著簡單進行試算會發現,數字重複到一個程度後,會進入循環,

所以我們建立一個list, 把出現過的數字都加到list中

迴圈的中止條件就在於 是否 進入到重複的數字



class Solution:
    def isHappy(self, n: int) -> bool:
        nums=[]
        '''為了避免陷入無窮迴圈,我們把出現過的紀錄在list'''
        while n not in nums:
            res=0
            nums.append(n)#將這次的n記錄到List中
            for i in str(n):
                res += int(i)**2
            n = res
        return n == 1
-----------------------------------------
參考解答

class Solution:
    def isHappy(self, n: int) -> bool:
        hset = set()
        while n != 1:
            if n in hset: return False
            hset.add(n)
            n = sum([int(i) ** 2 for i in str(n)])
        else:
            return True

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁