Python简单逻辑程序

问题描述 投票:0回答:1

问题:足够强大

您的程序将获得一个数字 n 作为输入。打印大于该数字的 2 的第一个幂。例如,如果 num 是 6,那么您应该打印 8,因为 2 的立方是 8,而 2 的平方只有 4,所以不够大。

答案:

n = int(input())
i = 1
while n > 0:
  if 2**i > n:
      print(2**i)
      break
  i += 1

以上是我想到的答案。我尝试使用 for 循环和许多其他变体,但没有成功。

这是来自 Perse Coding Team Challenge [PCTC Sample R2 Q3] 的问题。我得到 8/10,最后一个测试用例显示运行时错误,这是一个非常简单的代码,我不知道为什么它显示运行时错误。

网站链接:https://pctc.cuttle.org/index.php?action=user_competitions

python logic
1个回答
0
投票
import math

n = int(input("Enter a number: "))
next_power_of_2 = 2 ** (math.ceil(math.log2(n)))
print(next_power_of_2)

尝试这个没有循环的解决方案:P

© www.soinside.com 2019 - 2024. All rights reserved.