剑指Offer(Java版)第三十八题:把只包含质因子2、3和5的数称作丑数,Ugly Number。 例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。 求按从小到大的顺序的第N个丑数。

/*

把只包含质因子2、3和5的数称作丑数(Ugly Number)。

例如6、8都是丑数,但14不是,因为它包含质因子7。

习惯上我们把1当做是第一个丑数。

求按从小到大的顺序的第N个丑数。

*/

public class Class38 {

public int GetUglyNumber_Solution(int index){

if(index <= 0){

return 0;

}

int count = 0;

int uglyNumber = 0;

int start = 1;

while(count < index){

if(findUglyNumber(start) == true){

uglyNumber = start;

count++;

start++;

}else{

start++;

}

}

return uglyNumber;

}

public boolean findUglyNumber(int index){

if(index <= 0){

return false;

}

while(true){

if(index == 1 || index == 2 || index == 3 || index == 5){

return true;

}else if(index % 2 == 0){

index /= 2;

}else if(index % 3 == 0){

index /= 3;

}else if(index % 5 == 0){

index /= 5;

}else{

return false;

}

}

}

public void test(){

int index = 20;

System.out.println(GetUglyNumber_Solution(index));

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Class38 c = new Class38();

c.test();

}

}