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, 8are ugly while14is not ugly since it includes another prime factor7.
Note that
1is typically treated as an ugly number.
丑數(shù)就是分解因子之后只含有2,3,5的數(shù)就是丑數(shù),題目是判斷一個(gè)整數(shù)是不是丑數(shù),簡(jiǎn)單到只有這一種解法,沒(méi)有別的了
My Solution
(Java) Version 1 Time: 2ms:
判斷性質(zhì)先跟著定義走,既然丑數(shù)是又2,3,5相乘得來(lái)的,那就除回去,先是用2除,除到除不盡了,就用3除,再用5除,如果是丑數(shù)的話,那肯定最后會(huì)得到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;
}
}