剑指offer系列源码-丑数

题目1214:丑数
时间限制:1 秒内存限制:32 兆特殊判题:否提交:1700解决:756
题目描述:
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
输入:
输入包括一个整数N(1<=N<=1500)。
输出:
可能有多组测试数据,对于每组数据,
输出第N个丑数。
样例输入:
3
样例输出:
3

#include <iostream>
#include<stdio.h>
using namespace std;
int Min(int a,int b,int c){
  int min = (a<b)?a:b;
  return min<c?min:c;
}
int getUglyNumber(int index){
    if(index<=0){
        return 0;
    }
    int * pUglyNumbers = new int[index];
    pUglyNumbers[0] = 1;
    int nextUglyIndex = 1;
    int* pMultiply2 = pUglyNumbers;
    int* pMultiply3 = pUglyNumbers;
    int* pMultiply5 = pUglyNumbers;
    while(nextUglyIndex<index){
        int min = Min(*pMultiply2*2,*pMultiply3*3,*pMultiply5*5);
        pUglyNumbers[nextUglyIndex] = min;
        while(*pMultiply2*2<=pUglyNumbers[nextUglyIndex]){
            ++pMultiply2;
        }
        while(*pMultiply3*3<=pUglyNumbers[nextUglyIndex]){
            ++pMultiply3;
        }
        while(*pMultiply5*5<=pUglyNumbers[nextUglyIndex]){
            ++pMultiply5;
        }
        nextUglyIndex++;
    }
    return pUglyNumbers[nextUglyIndex-1];
}
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        printf("%d\n",getUglyNumber(n));
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值