每日一题(43) - 丑数

本文深入探讨了如何通过编程实现对丑数的判断与生成,包括算法逻辑、代码实现及核心思路解析。

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

题目来自剑指Offer

题目:


题目换句话说:丑数就是连续除以2,3,5,之后商为1的数.

代码:

bool IsUglyNum(int nNum)
{
	//消除因子2
	while (nNum % 2 == 0)
	{
		nNum /= 2;
	}
	//消除因子3
	while (nNum % 3 == 0)
	{
		nNum /= 3;
	}
	//消除因子5
	while (nNum % 5 == 0)
	{
		nNum /= 5;
	}

	if (nNum == 1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

题目思路:丑数乘以2,3,5后仍是丑数。

具体来说:根据现有丑数,每次扩展一个丑数。

(1)使用三个指针nCurOne,nCurTwo,nCurThree用来分别产生乘以2,3,5后的候选丑数。

(2)之后取三个候选丑数的最小值,作为本次扩展的丑数。

(3)让产生的候选丑数等于本次扩展丑数的指针都往前走一步。

注意:三个指针总是指向其待扩展的丑数

代码:

#include <iostream>
using namespace std;

const int SIZE = 10000; 

int Min(int x,int y,int z)
{
	if (x < y)
	{
		if (x < z) //y > x,z > x
		{
			return x;
		}
		else //y>x,x>=z
		{
			return z;

		}
	}
	else 
	{
		if (z > y)//x > y
		{
			return y;
		}
		else //x>y,y>z
		{
			return z;
		}
	}
}

int UglyNum(int nIndex)
{
	int nArrUgly[SIZE];
	
	int nCurTwo = 0;
	int nCurThree = 0;
	int nCurFive = 0;
	int nCount = 1;
	int nCurUgly = 0x3f3f3f;

	nArrUgly[0] = 1;
	while (nCount < nIndex)
	{
		nCurUgly = Min(nArrUgly[nCurTwo] * 2,nArrUgly[nCurThree] * 3,nArrUgly[nCurFive] * 5);
		nArrUgly[nCount++] = nCurUgly;
		if (nArrUgly[nCurTwo] * 2 == nCurUgly)
		{
			nCurTwo++;
		}
		if (nArrUgly[nCurThree] * 3 == nCurUgly)
		{
			nCurThree++;
		}
		if (nArrUgly[nCurFive] * 5 == nCurUgly)
		{
			nCurFive++;
		}
	}
	return nCurUgly;
}

int main()
{
	cout<<UglyNum(1500)<<endl;
	system("pause");
	return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值