微软面试100题-64


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();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值