题目:
Given two non-negative integers x
and y
, an integer is powerful if it is equal to x^i + y^j
for some integers i >= 0
and j >= 0
.
Return a list of all powerful integers that have value less than or equal to bound
.
You may return the answer in any order. In your answer, each value should occur at most once.
example:
Input: x = 2, y = 3, bound = 10 Output: [2,3,4,5,7,9,10] Explanation: 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2
没想到什么好方法,就简单的循环判断。要注意的地方有几个:不能有重复的输出,所以我每次确定要数字后都会用find()函数来看当前数字是不是已经存入vector;x或y等于1时有太多重复数字,会超时,所以要单独考虑;x和y同时等于1时有两种情况,一种是bound大于等于2,那只要返回2,如果小于2,就返回空vector。
第一次参加LeetCode的每周比赛遇到了大概十分钟无法连接上网页的问题,不知道是不是每次都会这样,下次以防万一还是能提交的先提交一遍。
代码:
vector<int> powerfulIntegers(int x, int y, int bound) {
vector<int> re;
if(x == 1 && y == 1){
vector<int> one;
one.push_back(2);
return one;
}
if(x == 1){
int j = 0;
while((1+pow(y,j) <= bound)){
int temp = 1+pow(y,j);
re.push_back(temp);
j++;
}
}
else if(y == 1){
int j = 0;
while((1+pow(x,j) <= bound)){
int temp = 1+pow(x,j);
re.push_back(temp);
j++;
}
}
else{
int i = 0, j = 0;
int temp = pow(x,i) + pow(y,j);
while(temp <= bound){
while(temp <= bound){
if(re.size() == 0 || find(re.begin(),re.end(),temp) == re.end())
re.push_back(temp);
j ++;
temp = pow(x,i) + pow(y,j);
}
i ++;
j = 0;
temp = pow(x,i) + pow(y,j);
}
}
return re;
}