LintCode: 丑数II

本文介绍了一种计算第n个丑数的方法,丑数定义为仅包含2、3和5作为质因数的正整数。通过一个不规范使用的递归算法示例,展示了如何判断一个数是否为丑数,并最终找到指定位置的丑数。

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

题目:计算第n个丑数的值,如输入9,输出10。丑数:只包含2或3或5为因数的数是丑数。如8=2x2x2,6=2x3,12=2x2x3,所以8,6,12都是丑数;14=2x7,所以14不是丑数。

超时解法(由于不规范使用递归导致超时。。):

public class Solution {
    /*
     * @param n: An integer
     * @return: the nth prime number as description.
     */
    public int nthUglyNumber(int n) {
        // write your code here
        int i = 0;
        int nCount = 1;  // 从1-n计数
        while (nCount <= n) {
            i++;
            if (isUglyNumber(i)) {
                // 如果i是丑数,计数值+1
                nCount++;  
            }
        }
        return i;
    }
    
    /**
     * 判断一个数是否是丑数
     */
    public boolean isUglyNumber(int n) {
        if (n == 1) {
          // 递归退出条件,n=1
          return true;
        } else if (n % 2 == 0) {
            // 说明可以被2整除
            return isUglyNumber(n / 2);
        } else if (n % 3 == 0) {
            // 说明可以被3整除
            return isUglyNumber(n / 3);
        } else if (n % 5 == 0) {
            // 说明可以被5整除
            return isUglyNumber(n / 5);
        } else {
            return false;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值