题目描述:
思路:
首先计算出bound对于x或者y的开根
然后计算他们的和,输出在bound范围内的数
注意:当有1时,会出现超时现象(无限循环),进行特殊处理
代码如下:
class Solution {
public:
int powernum(int m,int n){
int sum=0;
if(m==1) return n;
while(pow(m,sum)<=n){
sum++;
}
return sum;
}
vector<int> powerfulIntegers(int x, int y, int bound) {
vector<int>nums;
map<int,int>cnt;
if(x==1||y==1){
if(x==1&&y!=1){
int temp=powernum(y,bound);
for(int i=0;i<temp;i++){
for(int j=0;j<=1;j++){
cnt[pow(y,i)+pow(x,j)]++;
if(cnt[pow(y,i)+pow(x,j)]==1&&pow(y,i)+pow(x,j)<=bound)
nums.push_back(pow(y,i)+pow(x,j));}
}
}
if(x!=1&&y==1){
int temp=powernum(x,bound);
for(int i=0;i<temp;i++){
for(int j=0;j<=1;j++){
cnt[pow(x,i)+pow(y,j)]++;
if(cnt[pow(x,i)+pow(y,j)]==1&&pow(x,i)+pow(y,j)<=bound)
nums.push_back(pow(x,i)+pow(y,j));}
}
}
if(x==1&&y==1){
if(2<=bound){
nums.push_back(2);
return nums;}
return nums;
}
}
int a=powernum(x,bound);
int b=powernum(y,bound);
for(int i=0;i<min(18,a);i++){
for(int j=0;j<min(18,b);j++){
cnt[pow(x,i)+pow(y,j)]++;
if((cnt[pow(x,i)+pow(y,j)]==1)&&(pow(x,i)+pow(y,j)<=bound))
nums.push_back(pow(x,i)+pow(y,j));
}
}
return nums;
}
};