简单题
Total Accepted: 32635 Total Submissions: 94009 Difficulty: Easy
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.
Discuss中总有惊喜:
Java:
for (int i=2; i<6 && num>0; i++)
while (num % i == 0)
num /= i;
return num == 1;
Python:
for p in 2, 3, 5:
while num % p == 0 < num:
num /= p
return num == 1
C++:(其中&&之后的num怎么理解?)
for (int i=; i< && num; i++)
while (num % i == )
num /= i;
return num == ;
自己的:
C++:
class Solution {
public:
bool isUgly(int num) {
if (num <= )
return false;
if (num == )
return true; while (num != ) {
if (num % == ) {
num = num / ;
}
else if (num % == ) {
num = num / ;
}
else if (num % == ) {
num = num / ;
}
else{
return false;
}
}
return true;
}
};