263. Ugly Number && 264. Ugly Number II

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

0是一个spcial case, 当num>1的时候,分别对它进行检测,如果是丑数的话最后的结果应该是1.(不知道为啥一开始最后的判断条件写成了0)

class Solution {
public:
    bool isUgly(int num) {
        if(num == 0) return false;
        while(num > 1){
            if(num % 2 == 0) num /= 2;
            else if(num % 3 == 0) num /= 3;
            else if(num % 5 == 0) num /= 5;
            else return false;
        }
        return num == 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, and n does not exceed 1690.

这题是DP的思路,首先我们知道1是第一个丑数,然后之后的丑数无非是1*2, 1*3, 1*5,之后的丑数也是由这些数生成的,因此从1开始,用3个下标分别记录该*2 *3 *5的数的位置,然后每次进行比较,选出最小的push到dp数组中.

class Solution {
public:
    int nthUglyNumber(int n) {
        if(n <= 0) return false;
        if(n == 1) return 1;
        vector<int> dp(n);
        dp[0] = 1;
        int idx2 = 0, idx3 = 0, idx5 = 0;
        for(int i = 1; i != n; ++ i){
            dp[i] = min(dp[idx2]*2, min(dp[idx3]*3, dp[idx5]*5));
            if(dp[i] == dp[idx2]*2) idx2++;
            if(dp[i] == dp[idx3]*3) idx3++;
            if(dp[i] == dp[idx5]*5) idx5++;
        }
        return dp[n-1];
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值