剑指offer-丑数

27.丑数

题目内容:

代码及思路:

这道题我在之前leetcode的题目中也有出现过,具体可以对照学习。这道题不同之处就在于需要从小到大的顺序找出第N个丑数。

1.逐个数字进行判断,但不高效

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class solution
{
	public:
		//只包含质因子2、3、5的数字称为丑数,因此只要对是否存在这三个因子进行分析即可
		int GetUglyNumber_Solution(int index)
		{
			if (index <= 0)
				return 0;
			int num = 0;
			int countofugly = 0;
			while (countofugly < index)
			{
				num++;
				if (IsUgly(num))
				{
					countofugly++;
				}	
			}
			return num;
			
		}
		bool IsUgly(int number)
		{
			if (number < 1)
				return false;
			while (number != 1)
			{
				if (number % 2 == 0)
					number /= 2;
				else if (number % 3 == 0)
					number /= 3;
				else if (number % 5 == 0)
					number /= 5;
				else
					return false;
			}
			return true;
		}
};

void main()
{
	solution* object = new solution;
	int num;
	int index;
	cin >> index;
	num = object->GetUglyNumber_Solution(index);
	cout << num << endl;
	
}

2.更高效的方法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值