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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
//首先思路:题目说的很清楚,所谓丑数,就是那些因子只含2,3,5的数
//呢么根据丑陋数的定义,我们将给定数除以2、3、5,直到无法整除,也就是除以2、3、5的余数不再为0时停止
//这时如果得到1,说明是所有因子都是2或3或5,如果不是1,则不是丑陋数。
class Solution {
public:
bool isUgly(int num) {
if(num<=0)
return false;
if(num==1)
return true;
while(num>=2 && num%2==0) //因子2已经被除完
num/=2;
while(num>=3 && num%3==0)
num/=3;
while(num>=5 && num%5==0)
num/=5;
return num==1;
}
};
<LeetCode OJ> Ugly Number【263】
原文:http://blog.csdn.net/ebowtang/article/details/50408921