l263 ugly number

题目描述

1
2
3
4
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.
For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.

解题思路

  • 判断n是否能被2,3,5整除,如果不可以直接返回false
  • 如果可以将n替换为n/[2,3,5]后,再进行判断

Go实现1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func (num int) bool {
if num<=0{
return false
}
if num == 1 {
return true
}

for num >1 {
flag:= false
for _,x := range []int{2,3,5}{
if num%x==0 {
num = num/x
flag=true
}
}
if !flag {
return false
}
}

return true

}

Go实现2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func (num int) bool {
if num<=0{
return false
}
if num == 1 {
return true
}

for _,x := range []int{2,3,5}{
for num%x==0 {
num = num/x
}
}

return num == 1
}