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
分析:
判断一个数是否为丑数,即质数因子只包含2,3,5。只要除以2或3或5的余数不为0,就除以相应的数,最后判断是否为1即可。特别的,1为丑数。
class Solution {
public:
bool isUgly(int num) {
if(num <= 0)
return false;
if(num == 1)
return true;
while(!(num%2) || !(num%3) || !(num%5))
{
if(!(num%2))
num /= 2;
if(!(num%3))
num /= 3;
if(!(num%5))
num /= 5;
}
if(num == 1)
return true;
else
return false;
}
};