LeetCode(263) Ugly Number (264)Ugly Number II

263题目:ugly number是因数只包含2,3,5的数。判断一个数是不是ugly number

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.

解:直接检查除掉2,3,5外还有没有其他的因数。

代码:

class Solution {
public:
    bool isUgly(int num) {
        if(num<=0) return false;
        while(num>1)
        {
            if(num%5==0) num/=5;
            else if(num%3==0) num/=3;
            else if(num%2==0) num/=2;
            else return false;
        }
        return true;
    }
};
264题目:

求第n个UglyNumber

解法:
分成三个序列:

L1:1,1*2,2*2,3*2,4*2,5*2,6*2,8*2,...

L2:1,1*3,2*3,3*3,4*3,5*3,6*3,8*3,...

L3:1,1*5,2*5,3*5,4*5,5*5,6*5,8*5,...

每个序列的数字分别是已生成的UglyNumber乘以2,乘以3,乘以5。

用三个变量index1,index2,index3表示当前三个序列最后一个数字在已生成的UglyNumber集合中的下标。

新生成的UglyNumber就是L1,L2,L3序列的最后一个数分别乘以2,乘以3,乘以5的最小值。

复杂度:O(n)。
代码:

class Solution {
public:
    int nthUglyNumber(int n) {
        int index1=0,index2=0,index3=0;
        vector<int> nums;nums.push_back(1);
        for(int i=1;i<n;i++)
        {
            int cur;
            int t1=nums[index1]*2,t2=nums[index2]*3,t3=nums[index3]*5;
            if(t1<=t2&&t1<=t3) {index1++;cur=t1;}
            if(t2<=t1&&t2<=t3) {index2++;cur=t2;}
            if(t3<=t1&&t3<=t2) {index3++;cur=t3;}
            nums.push_back(cur);
        }
        return nums[n-1];
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值