目录/Table of Content
263. Ugly Number (丑数)
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目描述
这道题目先给出了丑数的定义是:一个只能被2、3或者5整除的正整数。然后,现在需要一个程序,以此帮助判断一个任意输入的数字是否丑数。
例如,6可以只被2和3整除 (6=2x3) 但14不能 (14=2x7),所以只有8是丑数。
题目原文(英语)
Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.
Note:
1. 1 is typically treated as an ugly number.
2. Input is within the 32-bit signed integer range: [−231, 231 − 1].
解题方式
我的方法很简单,就是用while-loop的方法一直把输入数字分别除以2、3和5,只要其中一项的馀数是0就迭代下去,直到完全整除或者三项数字都无法把它整除。
这个方法好的地方在于不需要太多额外的空间,而且时间複杂度低,对于大数字都可以在短时间內处理好。
时间复杂度:O(
l
o
g
2
N
log_2N
log2N)
空间复杂度:O(
1
1
1)
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
while True:
if num % 2 == 0:
num = num // 2
elif num % 3 == 0:
num = num // 3
elif num % 5 == 0:
num = num // 5
else:
break
if num > 1:
return False
elif num == 1:
return True