Ugly Number

import java.util.ArrayList;

/**
* Created by seven_hu on 2015/9/21.
*/

public class Solution3 {
/*
*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.
*
* */
public boolean isUgly(int num){
if(num==1) return true;
while(num%2==0) num=num/2;
while(num%3==0) num=num/3;
while(num%5==0) num=num/5;
return num==1;
}
/*
*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.
*
* */
public int nthUglyNum(int n){
if(n<1){
return 0;
}
int id2=0;
int id3=0;
int id5=0;
int rst=1;
ArrayList<Integer> arr=new ArrayList();
while(n>0){
arr.add(rst);
int v2=2*(arr.get(id2));
int v3=3*(arr.get(id3));
int v5=5*(arr.get(id5));
rst=Math.min(v2,Math.min(v3,v5));
if(rst==v2){
id2=id2+1;
}
if(rst==v3){
id3=id3+1;
}
if(rst==v5){
id5=id5+1;
}

}
return rst;
}
}
原文地址:https://www.cnblogs.com/hujingwei/p/4825646.html