欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[leetcode] 970. Powerful Integers

程序员文章站 2022-06-09 22:45:51
DescriptionGiven two positive 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...

Description

Given two positive 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 1:

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

Example 2:

Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]

Note:

  1. 1 <= x <= 100
  2. 1 <= y <= 100
  3. 0 <= bound <= 10^6

分析

题目的意思是:给定x,y,bound,x和y算指数次方求和,列举出所有小于bound的数。思路很直接,2**20次方大概是1024*1024约等于100 0000,符合bound的要求,x,y指数最多20次,所以写个双循环列举一下就行了,res保存其中满足条件的值。

代码

class Solution:
    def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
        res=set()
        for i in range(20):
            for j in range(20):
                ans=x**i+y**j
                if(ans<=bound):
                    res.add(ans)
                else:
                    break
                
        return list(res)

参考文献

solution

本文地址:https://blog.csdn.net/w5688414/article/details/110940540