在 Python 中检查一个数字的全部位数能否整除这个数字


假设我们有一个数字 n。我们必须检查其所有位数是否可以整除 n。

因此,如果输入类似于 n = 135,那么输出将为 True,因为 (135 ÷ 1 = 135)、(135 ÷ 3 = 45) 和 (135 ÷ 5 = 27)。

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

  • val := n
  • 当 val > 0 时,执行
    • d := val mod 10
    • 如果 n 不能被 d 整除,那么
      • 返回 False
    • val := (val / 10) 的商
  • 返回 True

让我们看看以下实现以获得更好的理解 −

示例

 实时演示

def is_divisible(n, d) :
   return d != 0 and n % d == 0
def solve(n) :
   val = n
   while (val > 0) :
      d = val % 10
   if not is_divisible(n, d):
      return False
      val = val // 10
   return True
n = 135
print(solve(n))

输入

135

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

输出

True

更新日期:2020 年 12 月 29 日

564 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告