检查给定数字是否是d的幂,其中d是2的幂(Python)


假设我们有一个数字n和另一个值x,我们必须检查它是否是x的幂,其中x是2的幂。

因此,如果输入类似于n = 32768,x = 32,则输出将为True,因为n是x³。

为了解决这个问题,我们将遵循以下步骤:

  • 从主方法执行以下操作:
  • cnt := 0
  • 如果n不为0,并且(n AND (n - 1))等于0,则
    • 当n > 1时,执行
      • n = n/2
      • cnt := cnt + 1
    • 返回cnt mod (log₂c) 是否等于0
  • 返回False

示例

让我们看下面的实现,以便更好地理解:

 在线演示

def find_pow_of_2(n):
   return (1 + find_pow_of_2(n / 2)) if (n > 1) else 0
def solve(n, c):
   cnt = 0
   if n and (n & (n - 1)) == 0:
      while n > 1:
         n >>= 1
         cnt += 1
      return cnt % (find_pow_of_2(c)) == 0
   return False
n = 32768
x = 32
print(solve(n, x))

输入

32768, 32

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

True

更新于:2021年1月18日

137 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告