263题目:ugly number是因数只包含2,3,5的数。判断一个数是不是ugly number
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.
解:直接检查除掉2,3,5外还有没有其他的因数。
代码:
class Solution {
public:
bool isUgly(int num) {
if(num<=0) return false;
while(num>1)
{
if(num%5==0) num/=5;
else if(num%3==0) num/=3;
else if(num%2==0) num/=2;
else return false;
}
return true;
}
};
264题目:
求第n个UglyNumber
解法:
分成三个序列:
L1:1,1*2,2*2,3*2,4*2,5*2,6*2,8*2,...
L2:1,1*3,2*3,3*3,4*3,5*3,6*3,8*3,...
L3:1,1*5,2*5,3*5,4*5,5*5,6*5,8*5,...
每个序列的数字分别是已生成的UglyNumber乘以2,乘以3,乘以5。
用三个变量index1,index2,index3表示当前三个序列最后一个数字在已生成的UglyNumber集合中的下标。
新生成的UglyNumber就是L1,L2,L3序列的最后一个数分别乘以2,乘以3,乘以5的最小值。
复杂度:O(n)。
代码:
class Solution {
public:
int nthUglyNumber(int n) {
int index1=0,index2=0,index3=0;
vector<int> nums;nums.push_back(1);
for(int i=1;i<n;i++)
{
int cur;
int t1=nums[index1]*2,t2=nums[index2]*3,t3=nums[index3]*5;
if(t1<=t2&&t1<=t3) {index1++;cur=t1;}
if(t2<=t1&&t2<=t3) {index2++;cur=t2;}
if(t3<=t1&&t3<=t2) {index3++;cur=t3;}
nums.push_back(cur);
}
return nums[n-1];
}
};