1,题目要求
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:
1 is typically treated as an ugly number.
Input is within the 32-bit signed integer range.
也就是所,如果一个数的素数因子只有2,3,5,则这个数就被称为ugly number。如果不是,则返回false。
例如14,虽然有2位因子,但是还有素数7作为因子,因此不是ugly number。
2,题目思路
首先,题目的意思非常直接,当然也可以用非常直接的办法来求:逐个对素数因子进行判断即可。但是也有别的更快捷的办法:
对于一个数字,如果它可以被2,3,5整除,则利用这种整除来缩小其自身。若是只有2,3,5作为因子,那么最后所得的结果一定为1。如果不然,最后结果一定不为1。
例如14,14是2的倍数,则将14缩小为14/2 = 7。而这个时候7不是2,3,5任何一个数的倍数,因此所得的结果也就不为1。
3,程序源码
class Solution {
public:
bool isUgly(int num) {
for(int i = 2;i<6 && num!=0;i++) //对可能输入的0做判断
{
while(num%i == 0)
num = num/i;
}
if(num == 1)
return true;
else
return false;
}
};