This is the first book of pleasure and delight 367 update, the first 395 Pian original
01 questions and look ready
Introduced today is the LeetCode
arithmetic problem in Easy
the first-level 229
title (overall title number is 970
). Given two positive integers x
and y
, if for some integer i >= 0
and is j >= 0
equal x^i + y^j
, then the integer is powerful.
The return value is less than or equal to the bound
list of all the powerful integers.
You can return the answers in any order. In your answer, each value should appear at most once. E.g:
Input: x = 2, y = 3 , bound 10 =
Output: [2,3,4,5,7,9,10]
Description:
2 + 0 = 2 ^ 3 ^ 0
3 = 2 + 1 ^ 3 ^ 0
4 + 0 = 2 ^ 3 ^ 1
5 = 2 + 1 ^ 3 ^ 1
. 7 = 2 ^ 2 ^ 3 1 +
9 = 2 ^ 3 ^ 3 + 0
10 = 0 + 2 ^ 2 ^ 3
Input: x = 3, y = 5 , bound = 15
Output: [2,4,6,8,10,14]
Note :
1 <= x <= 100
1 <= y <= 100
0 <= bound <= 10^6
02 The first solution
Can be directly translated title, no special skills, but need to note that, because the judgment condition x or y is less than a few parties bound
, if x
or y
as a time of 1, no power will be 1 1, would have been less than bound
, It will result in an endless loop.
public List<Integer> powerfulIntegers(int x, int y, int bound) {
Set<Integer> set = new HashSet<Integer>();
for (int i=0; Math.pow(x, i) < bound; i++) {
for (int j=0; Math.pow(y, j) < bound; j++) {
int sum = (int)Math.pow(x, i)+(int)Math.pow(y, j);
if (sum <= bound) {
set.add((int)sum);
}
// y等于1时,容易造成死循环,要结束掉
if (y == 1) {
break;
}
}
// x等于1时,容易造成死循环,要结束掉
if (x == 1) {
break;
}
}
return new ArrayList<>(set);
}
03 The second solution
For the first solution above, we can not help Math
class pow
method, multiplied by a total replacement, ideas are the same.
public List<Integer> powerfulIntegers2(int x, int y, int bound) {
Set<Integer> set = new HashSet<Integer>();
for (int i=1; i<bound; i *= x) {
for (int j=1; j<bound; j *= y) {
if (i+j <= bound) {
set.add(i+j);
}
if (y == 1) {
break;
}
}
if (x == 1) {
break;
}
}
return new ArrayList<>(set);
}
04 Summary
Thematic algorithm has been continuously day and more than seven months , the algorithm of feature articles 235 + articles, public Number dialog box reply [ data structures and algorithms ], [ algorithm ], [ data structures ] either a keyword to obtain a series of articles Collection .
That's all, if you have any good solution ideas, suggestions or other issues, you can exchange comments below, thumbs up, message forwarding and support is the greatest reward for me!