gly Number
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.
Hide Tags
Hide Similar Problems
(E) Happy Number (E) Count Primes (M) Ugly Number II
比较直接的一道题,如果不能被2,3,5整除,那肯定不会是,
因为它极有可能是一个更大的质数,例如11,或者仅仅以更大的质数为因子的数字,例如49。
如果能被其中某一个整除,那就用商来继续做判断,直到商小于等于5停止循环。
最后注意负数不算。
class Solution {
public:
bool isUgly(int num) {
while(num>5)
{
if((num%2)&&(num%3)&&(num%5))
return false;
if(0==num%2)
num /=2;
if(0==num%3)
num /=3;
if(0==num%5)
num /=5;
}
return (num>0);
}
};
8 ms.
No comments:
Post a Comment