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.更高效的方法