[264] Ugly number2

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.
题目要求使用程序找出第n个ugly number(能且仅能被2,3,5整除的数)

2. 解题思路

ugly number = 2^m*3^n*5^k
所以我们需要根据m,n,k的变化来得到ugly number的从小到大的序列

*2*3*5
235
2*235
2*22*35
3*22*35
3*22*32*5
4*23*32*5
5*23*32*5
5*24*32*5
6*24*33*5

当当前值为三个值中最小值时,指向的值在数组中后移一位

3. Code

class Solution {
public:
    int min(int a, int b)
    {
        return a<b ? a:b;
    }

    int nthUglyNumber(int n) {
        // num = 2^m*3^n*5^k;
        int* numbers = new int[n];  //保存所有1-n的丑数
        numbers[0] = 1;  // 第一个丑数是1
        int n1(0),n2(0),n3(0);
        int a(0),b(0),c(0);
        // 一次循环获得一个当前满足条件的最小值
        for(int i(1); i < n; ++i)
        {
            n1 = numbers[a]*2;
            n2 = numbers[b]*3;
            n3 = numbers[c]*5;
            int curMin = min(min(n1,n2),n3);
            numbers[i] = curMin;
            // 并列关系,在相同数值时一起向后移动
            if(n1 == curMin)
                a++;
            if(n2 == curMin)
                b++;
            if(n3 == curMin)
                c++;
        }
        return numbers[n-1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值