題目:
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
給定一數n,判斷它是不是ugly number
ugly number 是指質因數只有2,3,5的數
這題解法相當簡單且直觀
class Solution:
def isUgly(self, n: int) -> bool:
if n==0: #n是0直接回傳False
return False
while n%2==0:
n=n/2
while n%3==0:
n=n/3
while n%5==0:
n=n/5
return n==1
將n不斷除以2,3,5直到不能整除
若最後剩下的結果是1,即代表n是ugly number
最後執行時間32ms(faster than 93.71%)
那我們下題見