题目263:
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.
class Solution {
public boolean isUgly(int num) {
//判断一个数是否是丑数(只能被2、3、5的正数),注意:1属于典型的丑数.
if(num<=0)return false;
while(num!=1){
if(num%5==0){
num/=5;
}else if(num%3==0){
num/=3;
}else if(num%2==0){
num/=2;
}else{
return false;
}
}
return true;
}
}
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number, and n does not exceed 1690.
class Solution {
public int nthUglyNumber(int n) {
//找出第n个丑数(只能被2、3、5整除的正数),1是典型的丑数
//注意:不能使用逐个求出丑数,容易超时(n不超过1690即为Integer.MAX_VALUE)
int [] uglyNumber=new int[n];
//规律为:the first one, which is 1. Then
//k[1] = min( k[0]x2, k[0]x3, k[0]x5). The answer is k[0]x2. So we move 2's pointer to 1. Then we test:
//k[2] = min( k[1]x2, k[0]x3, k[0]x5). And so on.
int index2=0,index3=0,index5=0;
uglyNumber[0]=1;
for(int i=1;i<n;i++){
uglyNumber[i]=Math.min(uglyNumber[index2]*2,Math.min(uglyNumber[index3]*3,uglyNumber[index5]*5));
//找出最小的uglyNumber
if(uglyNumber[i]==uglyNumber[index2]*2)index2++;
if(uglyNumber[i]==uglyNumber[index3]*3)index3++;
if(uglyNumber[i]==uglyNumber[index5]*5)index5++;
}
return uglyNumber[n-1];
}
}