[LeetCode]263. Ugly Number&264. Ugly Number II

本文介绍了如何判断一个数是否为丑数,并提供了两种方法来找出第n个丑数。丑数是指只包含2、3、5这三个质因数的正整数。文章通过示例代码详细阐述了两种不同的算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

263 . Ugly Number
Easy

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.

2ms:

public boolean isUgly(int num) {
        if(num<=0)
            return false;

        while(num%2==0)
            num /= 2;
        while(num%3==0)
            num /= 3;
        while(num%5==0)
            num /= 5;

        return num==1;
}

264 . Ugly Number II
Medium

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.

72ms:

public int nthUglyNumber(int n) {
    int ans = 0;
    List<Integer> list1 = new LinkedList<Integer>();
    List<Integer> list2 = new LinkedList<Integer>();
    List<Integer> list3 = new LinkedList<Integer>();
    list1.add(1);
    list2.add(1);
    list3.add(1);
    for(int i = 0; i < n; i++){
        ans = Math.min(Math.min(list1.get(0),list2.get(0)), list3.get(0));
        if(ans == list1.get(0)) list1.remove(0);
        if(ans == list2.get(0)) list2.remove(0);
        if(ans == list3.get(0)) list3.remove(0);
        list1.add(ans*2);
        list2.add(ans*3);
        list3.add(ans*5);
    }
    return ans;
}

13ms:

public int nthUglyNumber(int n) {
    if (n <= 0)return 0;
    int[] index = new int[3];
    int[] uglyNumber = new int [n];
    uglyNumber[0] = 1;       
    int min_num = 1;   
    int i = 1;     
    while (n > 1) {     
        min_num = Math.min(2*uglyNumber[index[0]], Math.min(3*uglyNumber[index[1]], 5*uglyNumber[index[2]]));         
        uglyNumber[i] = min_num;     
        while(2*uglyNumber[index[0]]<=min_num) index[0]++;   
        while(3*uglyNumber[index[1]]<=min_num) index[1]++;       
        while(5*uglyNumber[index[2]]<=min_num) index[2]++;       
        i++;        
        n--;       
    }        
    return min_num;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值