c++ - 如何生成仅包含 0's and 9' 的数字

标签 c++ python-3.x algorithm loops generator

嗨,我想生成只包含 0 和 9 的数字,在 python 或 c++ 中无关紧要 我这样写:

for i in range(0,100):
    random_number = 9 * 10**i
    for j in range(0,i):
        second_sum = 9 *10 ** j
        random_number += second_sum
    print(random_number)


但输出是这样的

9
99
999
9999
99999
999999
9999999
99999999
999999999
9999999999
............
..............

但预期输出是

9
90
99
900
909
990
999
9000
9009
9090
9099
9900
9990
9999
--snip--

请大家帮帮我:)

最佳答案

根据@B.Go的评论,以下是替换的解决方案:

def generate(n=5):
    for i in range(1, 2**n):
        yield int('{:b}'.format(i).replace('1', '9'))

print([*generate(5)])

打印:

[9, 90, 99, 900, 909, 990, 999, 9000, 9009, 9090, 9099, 9900, 9909, 9990, 9999, 90000, 90009, 90090, 90099, 90900, 90909, 90990, 90999, 99000, 99009, 99090, 99099, 99900, 99909, 99990, 99999]

关于c++ - 如何生成仅包含 0's and 9' 的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229996/

相关文章:

algorithm - 创建复杂度更高的二叉搜索树

c++ - readdir() 显示不可见文件

c++ - 简单 Python 客户端和 C++ 服务器的示例

excel - 我可以在 python3 中从 excel 文件(不是 CSV)创建字典吗?

Python 拒绝写入访问,但我有手动访问权限,这可能是什么原因造成的?

javascript - 为什么字符串中的非空格元素不会更改为大写

c# - 俄罗斯方 block 游戏的朴素重力使用 2D 阵列作为运动场

c++ - 迭代器和 STL 容器

c++ - 找到唯一的毕达哥拉斯三元组

python - 使用 QT 运行 pytest 时出现致命的 Python 错误