How to return a list of numbers of the power of 2?

后端 未结 5 2022
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 10:56
def problem(n):
myList = []
for j in range(0, n):
    number = 2 ** j
    myList.append(number)
return myList

I want this code to return the powers

5条回答
  •  逝去的感伤
    2021-01-19 11:21

    Yet another simple and efficient solution (every step in O(1)) without the power operator:

    def problem(n):
        return [1 << i for i in range(n)]
    

    The 1 << i operations is a bitwise operation which translates to 2 ^ i for i integer positive.

    https://en.wikipedia.org/wiki/Arithmetic_shift

提交回复
热议问题