Processing math: 100%

检查一个数是否能被 2 的 n 次方整除,不使用 Python 中的算术运算符


假设我们有两个数字 x 和 n。我们需要检查 x 是否可以被 2^n 整除,不使用算术运算符。

因此,如果输入为 x = 32 n = 5,则输出将为 True,因为 32 = 2^5。

要解决这个问题,我们将遵循以下步骤 −

  • 如果 x AND (2^n - 1) 为 0,则
    • 返回 True
  • 返回 False

示例

让我们来看以下实现,以更好地理解 −

 在线演示

def solve (x, n):
   if (x & ((1 << n) - 1)) == 0:
      return True
   return False
x = 32
n = 5
print(solve(x, n))

输入

32, 5

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 月 19 日

346 次浏览

开启你的 职业生涯

通过完成课程获取认证

开始
广告