您的位置:首页 > 职场人生

微软面试100题-64

2016-05-02 23:56 357 查看

64. 寻找丑数(运算)。

题目:我们把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,

但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。

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

分析:这是一道在网络上广为流传的面试题,据说google曾经采用过这道题。
package com.algo.ms;

public class UglyNumber {

public int index2;
public int next2;
public int index3;
public int next3;
public int index5;
public int next5;
public int[] res;
public int num;
public UglyNumber(int num){
this.num = num;
res = new int[num];
}
public void findUglyNumber(){
for(int i = 0; i < num; i++){
if(i==0){
index2 = 0;
next2 = 2;
index2 = 0;
next3 = 3;
index5 = 0;
next5 = 5;
res[i] = 1;
}else{
int min = this.min(next2, next3, next5);
res[i] = min;
if(min == next2){
index2++;
next2 = 2*res[index2];

}
if(min == next3){
index3++;
next3 = 3*res[index3];

}
if(min == next5){
index5++;
next5 = 5*res[index5];

}
}
}

}

public int min( int min1, int min2, int min3){
if(min1 <= min2 && min1 <= min3)
return min1;
if(min2 <= min1 && min2 <= min3)
return min2;
if(min3 <= min1 && min3 <= min2)
return min3;
return min1;
}
public void printUgly(){
for(int i = 0; i < num; i++){
System.out.print(res[i]+",");
}
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
UglyNumber ugly = new UglyNumber(20);
ugly.findUglyNumber();
ugly.printUgly();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: