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.
这是今天才加上去的新题。没啥可说的。只要把ugly number的定义搞清楚就可以很好的写了。
因为prime factor只能为2,3,5。所以只要一个数不能被分解为只含有这三个数的乘式那么它就不是一个ugly number了。
代码如下。~
public class Solution { public boolean isUgly(int num) { if(num<=0){ return false; } if(num==1){ return true; } while(num!=1){ if(num%2==0){ num=num/2; }else if(num%3==0){ num=num/3; }else if(num%5==0){ num=num/5; }else{ return false; } } return true; } }
时间: 2024-10-28 16:04:55