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 while14
is not ugly since it includes another prime factor7
.
Note that
1
is typically treated as an ugly number.
丑數(shù)就是分解因子之后只含有2,3,5的數(shù)就是丑數(shù)调鲸,題目是判斷一個整數(shù)是不是丑數(shù),簡單到只有這一種解法狐榔,沒有別的了
My Solution
(Java) Version 1 Time: 2ms:
判斷性質(zhì)先跟著定義走礁芦,既然丑數(shù)是又2,3,5相乘得來的堆生,那就除回去盹舞,先是用2除,除到除不盡了佩微,就用3除佛纫,再用5除妓局,如果是丑數(shù)的話,那肯定最后會得到1呈宇,那這就是丑數(shù)
public class Solution {
public boolean isUgly(int num) {
if(num==1||num==2||num==3||num==5)return true;
if(num==0)return false;
while(num%2==0)num/=2;
while(num%3==0)num/=3;
while(num%5==0)num/=5;
if(num==1)return true;
return false;
}
}