You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用条件语句判断0-10000内整数是否仅含0和1?

如何判断0-10000内的整数仅包含数字0和1?

问题描述

给定范围在0到10000之间的整数,判断其是否仅由数字0和1组成:

  • 有效示例:num_1 = 1010(仅含0和1)
  • 无效示例:num_2 = 1234(不含0或1)、num_3 = 1034(包含0和1以外的数字)

限制条件

  • 禁止使用for、while循环
  • 禁止调用任何Python函数、方法(包括字符串方法、内置方法)
  • 仅可使用if、elif、else条件语句、简单变量赋值,以及and、or、not布尔运算符
  • 禁止使用列表、数组、集合、字典等对象

实现方案

由于数字范围是0到10000,最多包含5位数字(10000为特殊值,单独判断),我们可以通过数学运算拆分每一位数字,再逐一验证是否仅为0或1。

代码实现

def is_valid(num):
    # 处理10000的特殊情况:仅含1和0,有效
    if num == 10000:
        return True
    
    # 拆分每一位数字
    ten_thousands = num // 10000
    thousands = (num // 1000) % 10
    hundreds = (num // 100) % 10
    tens = (num // 10) % 10
    units = num % 10
    
    # 验证每一位是否是0或1
    valid_ten_thousands = (ten_thousands == 0) or (ten_thousands == 1)
    valid_thousands = (thousands == 0) or (thousands == 1)
    valid_hundreds = (hundreds == 0) or (hundreds == 1)
    valid_tens = (tens == 0) or (tens == 1)
    valid_units = (units == 0) or (units == 1)
    
    return valid_ten_thousands and valid_thousands and valid_hundreds and valid_tens and valid_units

示例验证

# 测试有效数字
print(is_valid(1010))  # 输出:True
# 测试无效数字
print(is_valid(1234))  # 输出:False
print(is_valid(1034))  # 输出:False
# 测试边界值
print(is_valid(0))     # 输出:True
print(is_valid(1))     # 输出:True
print(is_valid(10000)) # 输出:True

内容的提问来源于stack exchange,提问作者vamsi kintali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:20:44