Question:
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.
Analysis:
问题描述:写出一个程序判断一个数字是否为ugly number。ugly number是指仅包含2,3,5因子的数,例如8是丑数,而14就不是丑数,因为它还含有因子7. 1认为是丑数。
思路:当这个数可以被2/3/5整数就一直整出,知道最后,如果剩下的是1,说明该数是丑数;若不是1,则说明该数不是丑数。
Answer:
public class Solution { public boolean isUgly(int num) { if(num <= 0) return false; while(num != 0 && (num%2==0 || num%3==0 || num%5==0)) { if(num % 2 == 0) num = num / 2; if(num % 3 == 0) num = num / 3; if(num % 5 == 0) num = num / 5; } if(num == 1) return true; else return false; }}